@m4ike1/ion-tui 0.1.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 (196) hide show
  1. package/README.md +114 -0
  2. package/dist/alt-screen-search.d.ts +46 -0
  3. package/dist/alt-screen-search.d.ts.map +1 -0
  4. package/dist/alt-screen-search.js +282 -0
  5. package/dist/alt-screen-search.js.map +1 -0
  6. package/dist/autocomplete.d.ts +75 -0
  7. package/dist/autocomplete.d.ts.map +1 -0
  8. package/dist/autocomplete.js +749 -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 +24 -0
  15. package/dist/components/box.d.ts.map +1 -0
  16. package/dist/components/box.js +133 -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 +266 -0
  23. package/dist/components/editor.d.ts.map +1 -0
  24. package/dist/components/editor.js +2087 -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 +48 -0
  35. package/dist/components/input.d.ts.map +1 -0
  36. package/dist/components/input.js +417 -0
  37. package/dist/components/input.js.map +1 -0
  38. package/dist/components/loader.d.ts +33 -0
  39. package/dist/components/loader.d.ts.map +1 -0
  40. package/dist/components/loader.js +76 -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 +858 -0
  45. package/dist/components/markdown.js.map +1 -0
  46. package/dist/components/mouse-region.d.ts +12 -0
  47. package/dist/components/mouse-region.d.ts.map +1 -0
  48. package/dist/components/mouse-region.js +21 -0
  49. package/dist/components/mouse-region.js.map +1 -0
  50. package/dist/components/scroll-view.d.ts +68 -0
  51. package/dist/components/scroll-view.d.ts.map +1 -0
  52. package/dist/components/scroll-view.js +199 -0
  53. package/dist/components/scroll-view.js.map +1 -0
  54. package/dist/components/select-list.d.ts +53 -0
  55. package/dist/components/select-list.d.ts.map +1 -0
  56. package/dist/components/select-list.js +206 -0
  57. package/dist/components/select-list.js.map +1 -0
  58. package/dist/components/settings-list.d.ts +60 -0
  59. package/dist/components/settings-list.d.ts.map +1 -0
  60. package/dist/components/settings-list.js +252 -0
  61. package/dist/components/settings-list.js.map +1 -0
  62. package/dist/components/spacer.d.ts +12 -0
  63. package/dist/components/spacer.d.ts.map +1 -0
  64. package/dist/components/spacer.js +23 -0
  65. package/dist/components/spacer.js.map +1 -0
  66. package/dist/components/stack.d.ts +32 -0
  67. package/dist/components/stack.d.ts.map +1 -0
  68. package/dist/components/stack.js +111 -0
  69. package/dist/components/stack.js.map +1 -0
  70. package/dist/components/text.d.ts +19 -0
  71. package/dist/components/text.d.ts.map +1 -0
  72. package/dist/components/text.js +90 -0
  73. package/dist/components/text.js.map +1 -0
  74. package/dist/components/truncated-text.d.ts +13 -0
  75. package/dist/components/truncated-text.d.ts.map +1 -0
  76. package/dist/components/truncated-text.js +51 -0
  77. package/dist/components/truncated-text.js.map +1 -0
  78. package/dist/components/v-stack.d.ts +8 -0
  79. package/dist/components/v-stack.d.ts.map +1 -0
  80. package/dist/components/v-stack.js +26 -0
  81. package/dist/components/v-stack.js.map +1 -0
  82. package/dist/components/virtual-list.d.ts +51 -0
  83. package/dist/components/virtual-list.d.ts.map +1 -0
  84. package/dist/components/virtual-list.js +170 -0
  85. package/dist/components/virtual-list.js.map +1 -0
  86. package/dist/editor-component.d.ts +39 -0
  87. package/dist/editor-component.d.ts.map +1 -0
  88. package/dist/editor-component.js +2 -0
  89. package/dist/editor-component.js.map +1 -0
  90. package/dist/fuzzy.d.ts +16 -0
  91. package/dist/fuzzy.d.ts.map +1 -0
  92. package/dist/fuzzy.js +110 -0
  93. package/dist/fuzzy.js.map +1 -0
  94. package/dist/index.d.ts +34 -0
  95. package/dist/index.d.ts.map +1 -0
  96. package/dist/index.js +46 -0
  97. package/dist/index.js.map +1 -0
  98. package/dist/keybindings.d.ts +366 -0
  99. package/dist/keybindings.d.ts.map +1 -0
  100. package/dist/keybindings.js +331 -0
  101. package/dist/keybindings.js.map +1 -0
  102. package/dist/keys.d.ts +184 -0
  103. package/dist/keys.d.ts.map +1 -0
  104. package/dist/keys.js +1174 -0
  105. package/dist/keys.js.map +1 -0
  106. package/dist/kill-ring.d.ts +28 -0
  107. package/dist/kill-ring.d.ts.map +1 -0
  108. package/dist/kill-ring.js +44 -0
  109. package/dist/kill-ring.js.map +1 -0
  110. package/dist/latex.d.ts +10 -0
  111. package/dist/latex.d.ts.map +1 -0
  112. package/dist/latex.js +1285 -0
  113. package/dist/latex.js.map +1 -0
  114. package/dist/layout-node.d.ts +59 -0
  115. package/dist/layout-node.d.ts.map +1 -0
  116. package/dist/layout-node.js +12 -0
  117. package/dist/layout-node.js.map +1 -0
  118. package/dist/layout.d.ts +42 -0
  119. package/dist/layout.d.ts.map +1 -0
  120. package/dist/layout.js +404 -0
  121. package/dist/layout.js.map +1 -0
  122. package/dist/native-modifiers.d.ts +4 -0
  123. package/dist/native-modifiers.d.ts.map +1 -0
  124. package/dist/native-modifiers.js +13 -0
  125. package/dist/native-modifiers.js.map +1 -0
  126. package/dist/native-module-path.d.ts +7 -0
  127. package/dist/native-module-path.d.ts.map +1 -0
  128. package/dist/native-module-path.js +19 -0
  129. package/dist/native-module-path.js.map +1 -0
  130. package/dist/native-platform.d.ts +18 -0
  131. package/dist/native-platform.d.ts.map +1 -0
  132. package/dist/native-platform.js +42 -0
  133. package/dist/native-platform.js.map +1 -0
  134. package/dist/pty-host.d.ts +224 -0
  135. package/dist/pty-host.d.ts.map +1 -0
  136. package/dist/pty-host.js +347 -0
  137. package/dist/pty-host.js.map +1 -0
  138. package/dist/stdin-buffer.d.ts +56 -0
  139. package/dist/stdin-buffer.d.ts.map +1 -0
  140. package/dist/stdin-buffer.js +366 -0
  141. package/dist/stdin-buffer.js.map +1 -0
  142. package/dist/terminal-colors.d.ts +10 -0
  143. package/dist/terminal-colors.d.ts.map +1 -0
  144. package/dist/terminal-colors.js +59 -0
  145. package/dist/terminal-colors.js.map +1 -0
  146. package/dist/terminal-image.d.ts +118 -0
  147. package/dist/terminal-image.d.ts.map +1 -0
  148. package/dist/terminal-image.js +550 -0
  149. package/dist/terminal-image.js.map +1 -0
  150. package/dist/terminal.d.ts +123 -0
  151. package/dist/terminal.d.ts.map +1 -0
  152. package/dist/terminal.js +442 -0
  153. package/dist/terminal.js.map +1 -0
  154. package/dist/tui-alt-screen.d.ts +165 -0
  155. package/dist/tui-alt-screen.d.ts.map +1 -0
  156. package/dist/tui-alt-screen.js +1515 -0
  157. package/dist/tui-alt-screen.js.map +1 -0
  158. package/dist/tui-main-screen.d.ts +39 -0
  159. package/dist/tui-main-screen.d.ts.map +1 -0
  160. package/dist/tui-main-screen.js +594 -0
  161. package/dist/tui-main-screen.js.map +1 -0
  162. package/dist/tui.d.ts +431 -0
  163. package/dist/tui.d.ts.map +1 -0
  164. package/dist/tui.js +1142 -0
  165. package/dist/tui.js.map +1 -0
  166. package/dist/undo-stack.d.ts +17 -0
  167. package/dist/undo-stack.d.ts.map +1 -0
  168. package/dist/undo-stack.js +25 -0
  169. package/dist/undo-stack.js.map +1 -0
  170. package/dist/utils.d.ts +98 -0
  171. package/dist/utils.d.ts.map +1 -0
  172. package/dist/utils.js +1200 -0
  173. package/dist/utils.js.map +1 -0
  174. package/dist/word-navigation.d.ts +25 -0
  175. package/dist/word-navigation.d.ts.map +1 -0
  176. package/dist/word-navigation.js +96 -0
  177. package/dist/word-navigation.js.map +1 -0
  178. package/native/clipboard.h +170 -0
  179. package/native/darwin/README.md +22 -0
  180. package/native/darwin/build.sh +69 -0
  181. package/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  182. package/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  183. package/native/darwin/src/darwin-platform.m +93 -0
  184. package/native/linux/README.md +23 -0
  185. package/native/linux/build.sh +65 -0
  186. package/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  187. package/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  188. package/native/linux/src/clipboard-worker.h +70 -0
  189. package/native/linux/src/linux-platform-x11.c +274 -0
  190. package/native/napi.h +89 -0
  191. package/native/win32/README.md +31 -0
  192. package/native/win32/build.mjs +232 -0
  193. package/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  194. package/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  195. package/native/win32/src/win32-platform.c +241 -0
  196. package/package.json +62 -0
package/dist/tui.js ADDED
@@ -0,0 +1,1142 @@
1
+ /**
2
+ * Minimal TUI implementation with differential rendering
3
+ */
4
+ import { performance } from "node:perf_hooks";
5
+ import { getKeybindings } from "./keybindings.js";
6
+ import { isKeyRelease, isKeyRepeat, matchesKey } from "./keys.js";
7
+ import { isOsc11BackgroundColorResponse, parseOsc11BackgroundColor, parseTerminalColorSchemeReport, } from "./terminal-colors.js";
8
+ import { getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.js";
9
+ import { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, visibleWidth } from "./utils.js";
10
+ /**
11
+ * Dispatch an event to a component and retain the exact target and coordinate
12
+ * transform. Containers use this when forwarding events to nested children.
13
+ */
14
+ export function dispatchMouseEvent(component, event) {
15
+ const result = component.handleMouse?.(event);
16
+ if (!result)
17
+ return undefined;
18
+ if ("target" in result)
19
+ return result;
20
+ if (!result.handled && !result.capture && !result.focus)
21
+ return undefined;
22
+ return {
23
+ ...result,
24
+ handled: true,
25
+ ...(result.focus ? { focusTarget: component } : {}),
26
+ target: {
27
+ component,
28
+ originX: event.screenX - event.x,
29
+ originY: event.screenY - event.y,
30
+ width: event.width,
31
+ height: event.height,
32
+ },
33
+ };
34
+ }
35
+ /** Recreate local coordinates for a previously dispatched mouse target. */
36
+ export function retargetMouseEvent(event, target) {
37
+ return {
38
+ ...event,
39
+ x: event.screenX - target.originX,
40
+ y: event.screenY - target.originY,
41
+ width: target.width,
42
+ height: target.height,
43
+ };
44
+ }
45
+ /** Type guard to check if a component implements Focusable */
46
+ export function isFocusable(component) {
47
+ return component !== null && "focused" in component;
48
+ }
49
+ /** Type guard to check if a component implements AutocompleteHost */
50
+ export function isAutocompleteHost(component) {
51
+ if (component === null)
52
+ return false;
53
+ const host = component;
54
+ return typeof host.isShowingAutocomplete === "function" && typeof host.dismissAutocomplete === "function";
55
+ }
56
+ /**
57
+ * Cursor position marker - APC (Application Program Command) sequence.
58
+ * This is a zero-width escape sequence that terminals ignore.
59
+ * Components emit this at the cursor position when focused.
60
+ * TUI finds and strips this marker, then positions the hardware cursor there.
61
+ */
62
+ export const CURSOR_MARKER = "\x1b_pi:c\x07";
63
+ export { visibleWidth };
64
+ /** Parse a SizeValue into absolute value given a reference size */
65
+ function parseSizeValue(value, referenceSize) {
66
+ if (value === undefined)
67
+ return undefined;
68
+ if (typeof value === "number")
69
+ return value;
70
+ // Parse percentage string like "50%"
71
+ const match = value.match(/^(\d+(?:\.\d+)?)%$/);
72
+ if (match) {
73
+ return Math.floor((referenceSize * parseFloat(match[1])) / 100);
74
+ }
75
+ return undefined;
76
+ }
77
+ /**
78
+ * Container - a component that contains other components
79
+ */
80
+ export class Container {
81
+ children = [];
82
+ mouseLayout;
83
+ addChild(component) {
84
+ this.children.push(component);
85
+ }
86
+ removeChild(component) {
87
+ const index = this.children.indexOf(component);
88
+ if (index !== -1) {
89
+ this.children.splice(index, 1);
90
+ }
91
+ }
92
+ clear() {
93
+ this.children = [];
94
+ }
95
+ invalidate() {
96
+ for (const child of this.children) {
97
+ child.invalidate?.();
98
+ }
99
+ }
100
+ handleMouse(event) {
101
+ if (event.y < 0 || event.y >= event.height)
102
+ return undefined;
103
+ const mouseChildren = this.mouseLayout?.width === event.width
104
+ ? this.mouseLayout.children
105
+ : this.children.map((component) => ({ component, height: component.render(event.width).length }));
106
+ let childY = 0;
107
+ for (const { component: child, height: childHeight } of mouseChildren) {
108
+ if (event.y >= childY && event.y < childY + childHeight) {
109
+ const result = dispatchMouseEvent(child, {
110
+ ...event,
111
+ y: event.y - childY,
112
+ height: childHeight,
113
+ });
114
+ if (result?.focus && this.handleInput)
115
+ return { ...result, focusTarget: this };
116
+ return result;
117
+ }
118
+ childY += childHeight;
119
+ }
120
+ return undefined;
121
+ }
122
+ render(width) {
123
+ const lines = [];
124
+ const mouseChildren = [];
125
+ for (const child of this.children) {
126
+ const childLines = child.render(width);
127
+ mouseChildren.push({ component: child, height: childLines.length });
128
+ for (const line of childLines) {
129
+ lines.push(line);
130
+ }
131
+ }
132
+ this.mouseLayout = { width, children: mouseChildren };
133
+ return lines;
134
+ }
135
+ }
136
+ /**
137
+ * TUI - Main class for managing terminal UI with differential rendering
138
+ */
139
+ const SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07";
140
+ /** Composite overlay content into a terminal line at a fixed column. */
141
+ export function compositeTuiLine(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
142
+ if (isImageLine(baseLine))
143
+ return baseLine;
144
+ const afterStart = startCol + overlayWidth;
145
+ const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
146
+ const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
147
+ const beforePad = Math.max(0, startCol - base.beforeWidth);
148
+ const overlayPad = Math.max(0, overlayWidth - overlay.width);
149
+ const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
150
+ const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
151
+ const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
152
+ const afterPad = Math.max(0, afterTarget - base.afterWidth);
153
+ const result = base.before +
154
+ " ".repeat(beforePad) +
155
+ SEGMENT_RESET +
156
+ overlay.text +
157
+ " ".repeat(overlayPad) +
158
+ SEGMENT_RESET +
159
+ base.after +
160
+ " ".repeat(afterPad);
161
+ return visibleWidth(result) <= totalWidth ? result : sliceByColumn(result, 0, totalWidth, true);
162
+ }
163
+ export const VIEWPORT_TUI = Symbol.for("@m4ike1/ion-tui/viewport");
164
+ export function isViewportTUI(tui) {
165
+ return tui[VIEWPORT_TUI] === true;
166
+ }
167
+ export class TuiBase extends Container {
168
+ terminal;
169
+ focusedComponent = null;
170
+ inputListeners = new Set();
171
+ /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
172
+ onDebug;
173
+ renderRequested = false;
174
+ immediateRenderScheduled = false;
175
+ renderTimer;
176
+ lastRenderAt = 0;
177
+ static MIN_RENDER_INTERVAL_MS = 16;
178
+ showHardwareCursor = false;
179
+ clearOnShrink = false;
180
+ fullRedrawCount = 0;
181
+ stopped = false;
182
+ pendingOsc11BackgroundReplies = 0;
183
+ pendingOsc11BackgroundQueries = [];
184
+ terminalColorSchemeListeners = new Set();
185
+ terminalColorSchemeNotificationsEnabled = false;
186
+ /** Directory for debug/crash logs. When undefined, debug logging is disabled and crash dumps fall back to the OS temp directory. */
187
+ logDirectory;
188
+ // Overlay stack for modal components rendered on top of base content
189
+ focusOrderCounter = 0;
190
+ overlayStack = [];
191
+ renderedOverlayLayouts = [];
192
+ lastFocusTransition;
193
+ get hasOverlayEntries() {
194
+ return this.overlayStack.length > 0;
195
+ }
196
+ overlayFocusRestore = { status: "inactive" };
197
+ constructor(terminal, showHardwareCursor, logDirectory) {
198
+ super();
199
+ this.terminal = terminal;
200
+ this.logDirectory = logDirectory;
201
+ if (showHardwareCursor !== undefined) {
202
+ this.showHardwareCursor = showHardwareCursor;
203
+ }
204
+ }
205
+ resetRenderState() { }
206
+ beforeTerminalStart() { }
207
+ afterTerminalStart() { }
208
+ beforeTerminalStop(_options) { }
209
+ afterTerminalStop(_options) { }
210
+ get fullRedraws() {
211
+ return this.fullRedrawCount;
212
+ }
213
+ getShowHardwareCursor() {
214
+ return this.showHardwareCursor;
215
+ }
216
+ setShowHardwareCursor(enabled) {
217
+ if (this.showHardwareCursor === enabled)
218
+ return;
219
+ this.showHardwareCursor = enabled;
220
+ if (!enabled) {
221
+ this.terminal.hideCursor();
222
+ }
223
+ this.requestRender();
224
+ }
225
+ getClearOnShrink() {
226
+ return this.clearOnShrink;
227
+ }
228
+ /**
229
+ * Set whether to trigger full re-render when content shrinks.
230
+ * When true, empty rows are cleared when content shrinks.
231
+ * When false (default), empty rows remain (reduces redraws on slower terminals).
232
+ */
233
+ setClearOnShrink(enabled) {
234
+ this.clearOnShrink = enabled;
235
+ }
236
+ getFocusedComponent() {
237
+ return this.focusedComponent;
238
+ }
239
+ /** Last explicit focus transition, for debugging focus-stealing reports. */
240
+ getLastFocusTransition() {
241
+ return this.lastFocusTransition;
242
+ }
243
+ setFocus(component, options) {
244
+ this.setFocusInternal({ component, overlayFocusRestore: "clear", reason: options?.reason ?? "explicit" });
245
+ }
246
+ setFocusInternal({ component, overlayFocusRestore, reason, }) {
247
+ const previousFocus = this.focusedComponent;
248
+ let nextFocus = component;
249
+ const previousFocusedOverlay = previousFocus
250
+ ? this.overlayStack.find((entry) => entry.component === previousFocus && this.isOverlayVisible(entry))
251
+ : undefined;
252
+ const nextFocusIsOverlay = nextFocus ? this.overlayStack.some((entry) => entry.component === nextFocus) : false;
253
+ const restoreState = this.getVisibleOverlayFocusRestore();
254
+ if (nextFocus && !nextFocusIsOverlay) {
255
+ if (restoreState.status === "blocked" && restoreState.blockedBy === previousFocus) {
256
+ if (restoreState.resume.status === "focus-target" || !this.isComponentMounted(restoreState.blockedBy)) {
257
+ nextFocus = this.resolveBlockedOverlayFocusResume(restoreState);
258
+ }
259
+ else {
260
+ this.overlayFocusRestore = {
261
+ status: "blocked",
262
+ overlay: restoreState.overlay,
263
+ blockedBy: nextFocus,
264
+ resume: restoreState.resume,
265
+ };
266
+ }
267
+ }
268
+ else if (previousFocusedOverlay &&
269
+ restoreState.status !== "inactive" &&
270
+ restoreState.overlay === previousFocusedOverlay &&
271
+ !this.isOverlayFocusAncestor(previousFocusedOverlay, nextFocus)) {
272
+ this.overlayFocusRestore = {
273
+ status: "blocked",
274
+ overlay: previousFocusedOverlay,
275
+ blockedBy: nextFocus,
276
+ resume: { status: "restore-overlay" },
277
+ };
278
+ }
279
+ }
280
+ else if (nextFocus === null) {
281
+ if (restoreState.status === "blocked" && restoreState.blockedBy === previousFocus) {
282
+ nextFocus = this.resolveBlockedOverlayFocusResume(restoreState);
283
+ }
284
+ else if (overlayFocusRestore === "clear") {
285
+ this.clearOverlayFocusRestore();
286
+ }
287
+ }
288
+ if (isFocusable(this.focusedComponent)) {
289
+ this.focusedComponent.focused = false;
290
+ }
291
+ this.focusedComponent = nextFocus;
292
+ if (isFocusable(nextFocus)) {
293
+ nextFocus.focused = true;
294
+ }
295
+ this.lastFocusTransition = { from: previousFocus, to: nextFocus, reason };
296
+ const focusedOverlay = nextFocus
297
+ ? this.overlayStack.find((entry) => entry.component === nextFocus && this.isOverlayVisible(entry))
298
+ : undefined;
299
+ if (focusedOverlay) {
300
+ this.overlayFocusRestore = { status: "eligible", overlay: focusedOverlay };
301
+ }
302
+ }
303
+ clearOverlayFocusRestore() {
304
+ this.overlayFocusRestore = { status: "inactive" };
305
+ }
306
+ clearOverlayFocusRestoreFor(overlay) {
307
+ if (this.overlayFocusRestore.status !== "inactive" && this.overlayFocusRestore.overlay === overlay) {
308
+ this.clearOverlayFocusRestore();
309
+ }
310
+ }
311
+ resolveBlockedOverlayFocusResume(restoreState) {
312
+ if (restoreState.resume.status === "restore-overlay")
313
+ return restoreState.overlay.component;
314
+ this.clearOverlayFocusRestore();
315
+ return restoreState.resume.target;
316
+ }
317
+ getVisibleOverlayFocusRestore() {
318
+ const restoreState = this.overlayFocusRestore;
319
+ if (restoreState.status === "inactive")
320
+ return restoreState;
321
+ if (!this.overlayStack.includes(restoreState.overlay) || !this.isOverlayVisible(restoreState.overlay)) {
322
+ return { status: "inactive" };
323
+ }
324
+ return restoreState;
325
+ }
326
+ isOverlayFocusAncestor(entry, component) {
327
+ const visited = new Set();
328
+ let current = entry.preFocus;
329
+ while (current && !visited.has(current)) {
330
+ visited.add(current);
331
+ if (current === component)
332
+ return true;
333
+ current = this.overlayStack.find((overlay) => overlay.component === current)?.preFocus ?? null;
334
+ }
335
+ return false;
336
+ }
337
+ retargetOverlayPreFocus(removed) {
338
+ for (const overlay of this.overlayStack) {
339
+ if (overlay !== removed && overlay.preFocus === removed.component) {
340
+ overlay.preFocus = removed.preFocus;
341
+ }
342
+ }
343
+ }
344
+ getMountedRoots() {
345
+ return this.children;
346
+ }
347
+ isComponentMounted(component) {
348
+ return this.getMountedRoots().some((child) => this.containsComponent(child, component));
349
+ }
350
+ containsComponent(root, target) {
351
+ if (root === target)
352
+ return true;
353
+ if (!(root instanceof Container))
354
+ return false;
355
+ return root.children.some((child) => this.containsComponent(child, target));
356
+ }
357
+ /**
358
+ * Show an overlay component with configurable positioning and sizing.
359
+ * Returns a handle to control the overlay's visibility.
360
+ */
361
+ showOverlay(component, options) {
362
+ const entry = {
363
+ component,
364
+ ...(options === undefined ? {} : { options }),
365
+ preFocus: this.focusedComponent,
366
+ hidden: false,
367
+ focusOrder: ++this.focusOrderCounter,
368
+ };
369
+ this.overlayStack.push(entry);
370
+ // Only focus if overlay is actually visible
371
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
372
+ this.setFocus(component, { reason: "overlay-show" });
373
+ }
374
+ this.terminal.hideCursor();
375
+ this.requestRender();
376
+ // Return handle for controlling this overlay
377
+ return {
378
+ hide: () => {
379
+ const index = this.overlayStack.indexOf(entry);
380
+ if (index !== -1) {
381
+ this.clearOverlayFocusRestoreFor(entry);
382
+ this.retargetOverlayPreFocus(entry);
383
+ this.overlayStack.splice(index, 1);
384
+ // Restore focus if this overlay had focus
385
+ if (this.focusedComponent === component) {
386
+ const topVisible = this.getTopmostVisibleOverlay();
387
+ this.setFocus(topVisible?.component ?? entry.preFocus, { reason: "overlay-hide" });
388
+ }
389
+ if (this.overlayStack.length === 0)
390
+ this.terminal.hideCursor();
391
+ this.requestRender();
392
+ }
393
+ },
394
+ setHidden: (hidden) => {
395
+ if (entry.hidden === hidden)
396
+ return;
397
+ entry.hidden = hidden;
398
+ // Update focus when hiding/showing
399
+ if (hidden) {
400
+ this.clearOverlayFocusRestoreFor(entry);
401
+ // If this overlay had focus, move focus to next visible or preFocus
402
+ if (this.focusedComponent === component) {
403
+ const topVisible = this.getTopmostVisibleOverlay();
404
+ this.setFocus(topVisible?.component ?? entry.preFocus, { reason: "overlay-hide" });
405
+ }
406
+ }
407
+ else {
408
+ // Restore focus to this overlay when showing (if it's actually visible)
409
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
410
+ entry.focusOrder = ++this.focusOrderCounter;
411
+ this.setFocus(component, { reason: "overlay-visibility" });
412
+ }
413
+ }
414
+ this.requestRender();
415
+ },
416
+ isHidden: () => entry.hidden,
417
+ focus: () => {
418
+ if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry))
419
+ return;
420
+ entry.focusOrder = ++this.focusOrderCounter;
421
+ this.setFocus(component, { reason: "overlay-focus" });
422
+ this.requestRender();
423
+ },
424
+ unfocus: (unfocusOptions) => {
425
+ const isFocused = this.focusedComponent === component;
426
+ const restoreState = this.overlayFocusRestore;
427
+ const hasPendingRestore = restoreState.status !== "inactive" && restoreState.overlay === entry;
428
+ if (!isFocused && !hasPendingRestore)
429
+ return;
430
+ if (restoreState.status === "blocked" &&
431
+ restoreState.overlay === entry &&
432
+ this.focusedComponent === restoreState.blockedBy) {
433
+ if (unfocusOptions) {
434
+ this.overlayFocusRestore = {
435
+ status: "blocked",
436
+ overlay: entry,
437
+ blockedBy: restoreState.blockedBy,
438
+ resume: { status: "focus-target", target: unfocusOptions.target },
439
+ };
440
+ }
441
+ else {
442
+ this.clearOverlayFocusRestore();
443
+ }
444
+ this.requestRender();
445
+ return;
446
+ }
447
+ this.clearOverlayFocusRestoreFor(entry);
448
+ if (isFocused || unfocusOptions) {
449
+ const topVisible = this.getTopmostVisibleOverlay();
450
+ const fallbackTarget = topVisible && topVisible !== entry ? topVisible.component : entry.preFocus;
451
+ this.setFocus(unfocusOptions ? unfocusOptions.target : fallbackTarget, { reason: "overlay-unfocus" });
452
+ }
453
+ this.requestRender();
454
+ },
455
+ isFocused: () => this.focusedComponent === component,
456
+ getBounds: () => {
457
+ if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry) || !entry.bounds)
458
+ return undefined;
459
+ return { ...entry.bounds };
460
+ },
461
+ };
462
+ }
463
+ /** Hide the topmost overlay and restore previous focus. */
464
+ hideOverlay() {
465
+ const overlay = this.overlayStack[this.overlayStack.length - 1];
466
+ if (!overlay)
467
+ return;
468
+ this.clearOverlayFocusRestoreFor(overlay);
469
+ this.retargetOverlayPreFocus(overlay);
470
+ this.overlayStack.pop();
471
+ if (this.focusedComponent === overlay.component) {
472
+ // Find topmost visible overlay, or fall back to preFocus
473
+ const topVisible = this.getTopmostVisibleOverlay();
474
+ this.setFocus(topVisible?.component ?? overlay.preFocus, { reason: "overlay-hide" });
475
+ }
476
+ if (this.overlayStack.length === 0)
477
+ this.terminal.hideCursor();
478
+ this.requestRender();
479
+ }
480
+ /** Check if there are any visible overlays */
481
+ hasOverlay() {
482
+ return this.overlayStack.some((o) => this.isOverlayVisible(o));
483
+ }
484
+ /** Check if the focused component is a visible overlay */
485
+ isOverlayFocused() {
486
+ return this.overlayStack.some((entry) => entry.component === this.focusedComponent && this.isOverlayVisible(entry));
487
+ }
488
+ /**
489
+ * Dismiss the innermost Escape-dismissable layer. Order: open autocomplete
490
+ * on the focused component first, then (in subclasses) viewport layers such
491
+ * as transcript search, then forward to the topmost capturing overlay when
492
+ * focus drifted outside the overlay stack. Returns true when exactly one
493
+ * layer consumed the press; callers must not forward it further.
494
+ */
495
+ dismissInnermostLayer(data) {
496
+ const focused = this.focusedComponent;
497
+ if (isAutocompleteHost(focused) && focused.isShowingAutocomplete()) {
498
+ focused.dismissAutocomplete();
499
+ return true;
500
+ }
501
+ // Focus drifted outside the overlay stack while a capturing layer is
502
+ // open: the topmost layer owns Escape, so deliver it there instead of
503
+ // leaking the press to the unfocused base component below.
504
+ if (!this.isFocusInVisibleOverlay()) {
505
+ const topmost = this.getTopmostVisibleCapturingOverlay();
506
+ if (topmost?.handleInput) {
507
+ topmost.handleInput(data);
508
+ return true;
509
+ }
510
+ }
511
+ return false;
512
+ }
513
+ /** Topmost visible capturing overlay component, if any. */
514
+ getTopmostVisibleCapturingOverlay() {
515
+ return this.getTopmostVisibleOverlay()?.component;
516
+ }
517
+ /**
518
+ * Whether a component lives inside a visible overlay. With `capturingOnly`,
519
+ * non-capturing overlays do not count.
520
+ */
521
+ isComponentInVisibleOverlay(component, capturingOnly = false) {
522
+ return this.overlayStack.some((entry) => this.isOverlayVisible(entry) &&
523
+ (!capturingOnly || !entry.options?.nonCapturing) &&
524
+ (entry.component === component || this.containsComponent(entry.component, component)));
525
+ }
526
+ /** Whether keyboard focus currently sits inside a visible overlay. */
527
+ isFocusInVisibleOverlay(capturingOnly = false) {
528
+ return this.focusedComponent !== null && this.isComponentInVisibleOverlay(this.focusedComponent, capturingOnly);
529
+ }
530
+ /** Keep overlay containers as keyboard focus owners when a nested control is clicked. */
531
+ resolveMouseFocusTarget(component) {
532
+ for (let index = this.overlayStack.length - 1; index >= 0; index--) {
533
+ const overlay = this.overlayStack[index];
534
+ if (this.isOverlayVisible(overlay) && this.containsComponent(overlay.component, component)) {
535
+ return overlay.component;
536
+ }
537
+ }
538
+ return component;
539
+ }
540
+ /** Dispatch to the visually topmost overlay under the pointer. */
541
+ dispatchMouseToOverlay(event) {
542
+ for (let index = this.renderedOverlayLayouts.length - 1; index >= 0; index--) {
543
+ const layout = this.renderedOverlayLayouts[index];
544
+ if (event.screenX < layout.col ||
545
+ event.screenX >= layout.col + layout.width ||
546
+ event.screenY < layout.row ||
547
+ event.screenY >= layout.row + layout.height) {
548
+ continue;
549
+ }
550
+ const result = dispatchMouseEvent(layout.entry.component, {
551
+ ...event,
552
+ x: event.screenX - layout.col,
553
+ y: event.screenY - layout.row,
554
+ width: layout.width,
555
+ height: layout.height,
556
+ });
557
+ return result
558
+ ? {
559
+ hit: true,
560
+ result: result.focus ? { ...result, focusTarget: layout.entry.component } : result,
561
+ }
562
+ : { hit: true };
563
+ }
564
+ return { hit: false };
565
+ }
566
+ /** Check if an overlay entry is currently visible */
567
+ isOverlayVisible(entry) {
568
+ if (entry.hidden)
569
+ return false;
570
+ if (entry.options?.visible) {
571
+ return entry.options.visible(this.terminal.columns, this.terminal.rows);
572
+ }
573
+ return true;
574
+ }
575
+ /** Find the visual-frontmost visible capturing overlay, if any */
576
+ getTopmostVisibleOverlay() {
577
+ let topmost;
578
+ for (const overlay of this.overlayStack) {
579
+ if (overlay.options?.nonCapturing || !this.isOverlayVisible(overlay))
580
+ continue;
581
+ if (!topmost || overlay.focusOrder > topmost.focusOrder) {
582
+ topmost = overlay;
583
+ }
584
+ }
585
+ return topmost;
586
+ }
587
+ invalidate() {
588
+ for (const root of this.getMountedRoots())
589
+ root.invalidate();
590
+ for (const overlay of this.overlayStack)
591
+ overlay.component.invalidate();
592
+ }
593
+ start() {
594
+ this.stopped = false;
595
+ this.beforeTerminalStart();
596
+ this.terminal.start((data) => this.handleTerminalInput(data), () => this.requestRender());
597
+ this.afterTerminalStart();
598
+ this.terminal.hideCursor();
599
+ if (this.terminalColorSchemeNotificationsEnabled) {
600
+ this.terminal.write("\x1b[?2031h");
601
+ }
602
+ this.queryCellSize();
603
+ this.requestRender();
604
+ }
605
+ addInputListener(listener) {
606
+ this.inputListeners.add(listener);
607
+ return () => {
608
+ this.inputListeners.delete(listener);
609
+ };
610
+ }
611
+ removeInputListener(listener) {
612
+ this.inputListeners.delete(listener);
613
+ }
614
+ onTerminalColorSchemeChange(listener) {
615
+ this.terminalColorSchemeListeners.add(listener);
616
+ return () => {
617
+ this.terminalColorSchemeListeners.delete(listener);
618
+ };
619
+ }
620
+ setTerminalColorSchemeNotifications(enabled) {
621
+ if (this.terminalColorSchemeNotificationsEnabled === enabled) {
622
+ return;
623
+ }
624
+ this.terminalColorSchemeNotificationsEnabled = enabled;
625
+ if (!this.stopped) {
626
+ this.terminal.write(enabled ? "\x1b[?2031h" : "\x1b[?2031l");
627
+ }
628
+ }
629
+ queryCellSize() {
630
+ // Only query if terminal supports images (cell size is only used for image rendering)
631
+ if (!getCapabilities().images) {
632
+ return;
633
+ }
634
+ // Query terminal for cell size in pixels: CSI 16 t
635
+ // Response format: CSI 6 ; height ; width t
636
+ this.terminal.write("\x1b[16t");
637
+ }
638
+ stop(options = {}) {
639
+ this.stopped = true;
640
+ this.cancelRenderTimer();
641
+ if (this.terminalColorSchemeNotificationsEnabled) {
642
+ this.terminal.write("\x1b[?2031l");
643
+ }
644
+ this.beforeTerminalStop(options);
645
+ this.terminal.showCursor();
646
+ this.terminal.stop();
647
+ this.afterTerminalStop(options);
648
+ }
649
+ renderNow(force = false) {
650
+ if (force)
651
+ this.resetRenderState();
652
+ this.renderRequested = false;
653
+ this.cancelRenderTimer();
654
+ this.lastRenderAt = performance.now();
655
+ this.doRender();
656
+ }
657
+ requestRender(force = false) {
658
+ if (force) {
659
+ this.resetRenderState();
660
+ this.requestImmediateRender();
661
+ return;
662
+ }
663
+ if (this.renderRequested)
664
+ return;
665
+ this.renderRequested = true;
666
+ process.nextTick(() => this.scheduleRender());
667
+ }
668
+ requestImmediateRender() {
669
+ this.cancelRenderTimer();
670
+ this.renderRequested = true;
671
+ if (this.immediateRenderScheduled)
672
+ return;
673
+ this.immediateRenderScheduled = true;
674
+ process.nextTick(() => {
675
+ this.immediateRenderScheduled = false;
676
+ if (this.stopped || !this.renderRequested)
677
+ return;
678
+ // A previously queued scheduleRender() can create a timer before this
679
+ // callback runs. User input must preempt that throttled frame.
680
+ this.cancelRenderTimer();
681
+ this.renderRequested = false;
682
+ this.lastRenderAt = performance.now();
683
+ this.doRender();
684
+ });
685
+ }
686
+ cancelRenderTimer() {
687
+ if (!this.renderTimer)
688
+ return;
689
+ clearTimeout(this.renderTimer);
690
+ this.renderTimer = undefined;
691
+ }
692
+ scheduleRender() {
693
+ if (this.stopped || this.renderTimer || !this.renderRequested) {
694
+ return;
695
+ }
696
+ const elapsed = performance.now() - this.lastRenderAt;
697
+ const delay = Math.max(0, TuiBase.MIN_RENDER_INTERVAL_MS - elapsed);
698
+ this.renderTimer = setTimeout(() => {
699
+ this.renderTimer = undefined;
700
+ if (this.stopped || !this.renderRequested) {
701
+ return;
702
+ }
703
+ this.renderRequested = false;
704
+ this.lastRenderAt = performance.now();
705
+ this.doRender();
706
+ if (this.renderRequested) {
707
+ this.scheduleRender();
708
+ }
709
+ }, delay);
710
+ }
711
+ handleTerminalInput(data) {
712
+ if (this.consumeOsc11BackgroundResponse(data)) {
713
+ return;
714
+ }
715
+ if (this.consumeTerminalColorSchemeReport(data)) {
716
+ return;
717
+ }
718
+ if (this.inputListeners.size > 0) {
719
+ let current = data;
720
+ for (const listener of this.inputListeners) {
721
+ const result = listener(current);
722
+ if (result?.consume) {
723
+ return;
724
+ }
725
+ if (result?.data !== undefined) {
726
+ current = result.data;
727
+ }
728
+ }
729
+ if (current.length === 0) {
730
+ return;
731
+ }
732
+ data = current;
733
+ }
734
+ // Consume terminal cell size responses without blocking unrelated input.
735
+ if (this.consumeCellSizeResponse(data)) {
736
+ return;
737
+ }
738
+ // Global debug key handler (Shift+Ctrl+D)
739
+ if (matchesKey(data, "shift+ctrl+d") && this.onDebug) {
740
+ this.onDebug();
741
+ return;
742
+ }
743
+ // If focused component is an overlay, verify it's still visible
744
+ // (visibility can change due to terminal resize or visible() callback)
745
+ const focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);
746
+ if (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {
747
+ // Focused overlay is no longer visible, redirect to topmost visible overlay
748
+ const topVisible = this.getTopmostVisibleOverlay();
749
+ if (topVisible) {
750
+ this.setFocus(topVisible.component, { reason: "overlay-visibility" });
751
+ }
752
+ else {
753
+ this.setFocusInternal({
754
+ component: focusedOverlay.preFocus,
755
+ overlayFocusRestore: "preserve",
756
+ reason: "overlay-visibility",
757
+ });
758
+ }
759
+ }
760
+ const focusIsOverlay = this.overlayStack.some((o) => o.component === this.focusedComponent);
761
+ // Escape unwinds exactly one layer per press, innermost first, and a
762
+ // consumed press never leaks to the layer below. Presses only: repeats
763
+ // must not blow through stacked layers while the key is held.
764
+ const isEscapePress = !isKeyRelease(data) &&
765
+ !isKeyRepeat(data) &&
766
+ (matchesKey(data, "escape") || getKeybindings().matches(data, "tui.altScreen.searchClose"));
767
+ if (isEscapePress) {
768
+ // The focused layer gets first refusal before overlay restoration
769
+ // runs, so an autocomplete dropdown open above a dialog closes
770
+ // first and the next press reaches the dialog.
771
+ const focused = this.focusedComponent;
772
+ if (isAutocompleteHost(focused) && focused.isShowingAutocomplete()) {
773
+ focused.dismissAutocomplete();
774
+ // Keyboard input is latency-sensitive. Avoid the throttled timer
775
+ // path, where even setTimeout(0) can take a full 16 ms tick on Windows.
776
+ this.requestImmediateRender();
777
+ return;
778
+ }
779
+ }
780
+ if (!focusIsOverlay) {
781
+ const restoreState = this.getVisibleOverlayFocusRestore();
782
+ if (restoreState.status === "eligible") {
783
+ this.setFocus(restoreState.overlay.component, { reason: "overlay-restore" });
784
+ }
785
+ else if (restoreState.status === "blocked" && restoreState.blockedBy !== this.focusedComponent) {
786
+ if (restoreState.resume.status === "restore-overlay") {
787
+ this.setFocus(restoreState.overlay.component, { reason: "overlay-restore" });
788
+ }
789
+ else {
790
+ this.clearOverlayFocusRestore();
791
+ this.setFocus(restoreState.resume.target, { reason: "overlay-restore" });
792
+ }
793
+ }
794
+ }
795
+ // Escape unwinds exactly one layer per press, innermost first, and a
796
+ // consumed press never leaks to the layer below.
797
+ if (isEscapePress && this.dismissInnermostLayer(data)) {
798
+ // Keyboard input is latency-sensitive. Avoid the throttled timer path,
799
+ // where even setTimeout(0) can take a full 16 ms tick on Windows.
800
+ this.requestImmediateRender();
801
+ return;
802
+ }
803
+ // Pass input to focused component (including Ctrl+C)
804
+ // The focused component can decide how to handle Ctrl+C
805
+ if (this.focusedComponent?.handleInput) {
806
+ // Filter out key release events unless component opts in
807
+ if (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {
808
+ return;
809
+ }
810
+ this.focusedComponent.handleInput(data);
811
+ // Keyboard input is latency-sensitive. Avoid the throttled timer path,
812
+ // where even setTimeout(0) can take a full 16 ms tick on Windows.
813
+ this.requestImmediateRender();
814
+ }
815
+ }
816
+ consumeOsc11BackgroundResponse(data) {
817
+ if (this.pendingOsc11BackgroundReplies <= 0) {
818
+ return false;
819
+ }
820
+ if (!isOsc11BackgroundColorResponse(data)) {
821
+ return false;
822
+ }
823
+ const rgb = parseOsc11BackgroundColor(data);
824
+ this.pendingOsc11BackgroundReplies -= 1;
825
+ const query = this.pendingOsc11BackgroundQueries.shift();
826
+ if (query && !query.settled) {
827
+ query.settled = true;
828
+ if (query.timer) {
829
+ clearTimeout(query.timer);
830
+ query.timer = undefined;
831
+ }
832
+ query.resolve?.(rgb);
833
+ query.resolve = undefined;
834
+ }
835
+ return true;
836
+ }
837
+ consumeTerminalColorSchemeReport(data) {
838
+ const scheme = parseTerminalColorSchemeReport(data);
839
+ if (!scheme) {
840
+ return false;
841
+ }
842
+ for (const listener of this.terminalColorSchemeListeners) {
843
+ listener(scheme);
844
+ }
845
+ return true;
846
+ }
847
+ consumeCellSizeResponse(data) {
848
+ // Response format: ESC [ 6 ; height ; width t
849
+ const match = data.match(/^\x1b\[6;(\d+);(\d+)t$/);
850
+ if (!match) {
851
+ return false;
852
+ }
853
+ const heightPx = parseInt(match[1], 10);
854
+ const widthPx = parseInt(match[2], 10);
855
+ if (heightPx <= 0 || widthPx <= 0) {
856
+ return true;
857
+ }
858
+ setCellDimensions({ widthPx, heightPx });
859
+ // Invalidate all components so images re-render with correct dimensions.
860
+ this.invalidate();
861
+ this.requestRender();
862
+ return true;
863
+ }
864
+ /**
865
+ * Resolve overlay layout from options.
866
+ * Returns { width, row, col, maxHeight } for rendering.
867
+ */
868
+ resolveOverlayLayout(options, overlayHeight, termWidth, termHeight) {
869
+ const opt = options ?? {};
870
+ // Parse margin (clamp to non-negative)
871
+ const margin = typeof opt.margin === "number"
872
+ ? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }
873
+ : (opt.margin ?? {});
874
+ const marginTop = Math.max(0, margin.top ?? 0);
875
+ const marginRight = Math.max(0, margin.right ?? 0);
876
+ const marginBottom = Math.max(0, margin.bottom ?? 0);
877
+ const marginLeft = Math.max(0, margin.left ?? 0);
878
+ // Available space after margins
879
+ const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
880
+ const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
881
+ // === Resolve width ===
882
+ let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
883
+ // Apply minWidth
884
+ if (opt.minWidth !== undefined) {
885
+ width = Math.max(width, opt.minWidth);
886
+ }
887
+ // Clamp to available space
888
+ width = Math.max(1, Math.min(width, availWidth));
889
+ // === Resolve maxHeight ===
890
+ let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
891
+ // Clamp to available space
892
+ if (maxHeight !== undefined) {
893
+ maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
894
+ }
895
+ // Effective overlay height (may be clamped by maxHeight)
896
+ const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
897
+ // === Resolve position ===
898
+ let row;
899
+ let col;
900
+ if (opt.row !== undefined) {
901
+ if (typeof opt.row === "string") {
902
+ // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
903
+ const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
904
+ if (match) {
905
+ const maxRow = Math.max(0, availHeight - effectiveHeight);
906
+ const percent = parseFloat(match[1]) / 100;
907
+ row = marginTop + Math.floor(maxRow * percent);
908
+ }
909
+ else {
910
+ // Invalid format, fall back to center
911
+ row = this.resolveAnchorRow("center", effectiveHeight, availHeight, marginTop);
912
+ }
913
+ }
914
+ else {
915
+ // Absolute row position
916
+ row = opt.row;
917
+ }
918
+ }
919
+ else {
920
+ // Anchor-based (default: center)
921
+ const anchor = opt.anchor ?? "center";
922
+ row = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
923
+ }
924
+ if (opt.col !== undefined) {
925
+ if (typeof opt.col === "string") {
926
+ // Percentage: 0% = left, 100% = right (overlay stays within bounds)
927
+ const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
928
+ if (match) {
929
+ const maxCol = Math.max(0, availWidth - width);
930
+ const percent = parseFloat(match[1]) / 100;
931
+ col = marginLeft + Math.floor(maxCol * percent);
932
+ }
933
+ else {
934
+ // Invalid format, fall back to center
935
+ col = this.resolveAnchorCol("center", width, availWidth, marginLeft);
936
+ }
937
+ }
938
+ else {
939
+ // Absolute column position
940
+ col = opt.col;
941
+ }
942
+ }
943
+ else {
944
+ // Anchor-based (default: center)
945
+ const anchor = opt.anchor ?? "center";
946
+ col = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);
947
+ }
948
+ // Apply offsets
949
+ if (opt.offsetY !== undefined)
950
+ row += opt.offsetY;
951
+ if (opt.offsetX !== undefined)
952
+ col += opt.offsetX;
953
+ // Clamp to terminal bounds (respecting margins)
954
+ row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
955
+ col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
956
+ return { width, row, col, maxHeight };
957
+ }
958
+ resolveAnchorRow(anchor, height, availHeight, marginTop) {
959
+ switch (anchor) {
960
+ case "top-left":
961
+ case "top-center":
962
+ case "top-right":
963
+ return marginTop;
964
+ case "bottom-left":
965
+ case "bottom-center":
966
+ case "bottom-right":
967
+ return marginTop + availHeight - height;
968
+ case "left-center":
969
+ case "center":
970
+ case "right-center":
971
+ return marginTop + Math.floor((availHeight - height) / 2);
972
+ }
973
+ }
974
+ resolveAnchorCol(anchor, width, availWidth, marginLeft) {
975
+ switch (anchor) {
976
+ case "top-left":
977
+ case "left-center":
978
+ case "bottom-left":
979
+ return marginLeft;
980
+ case "top-right":
981
+ case "right-center":
982
+ case "bottom-right":
983
+ return marginLeft + availWidth - width;
984
+ case "top-center":
985
+ case "center":
986
+ case "bottom-center":
987
+ return marginLeft + Math.floor((availWidth - width) / 2);
988
+ }
989
+ }
990
+ /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
991
+ compositeOverlays(lines, termWidth, termHeight) {
992
+ if (this.overlayStack.length === 0) {
993
+ this.renderedOverlayLayouts = [];
994
+ return lines;
995
+ }
996
+ const result = [...lines];
997
+ for (const entry of this.overlayStack)
998
+ entry.bounds = undefined;
999
+ // Pre-render all visible overlays and calculate positions
1000
+ const rendered = [];
1001
+ let minLinesNeeded = result.length;
1002
+ const visibleEntries = this.overlayStack.filter((e) => this.isOverlayVisible(e));
1003
+ visibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);
1004
+ for (const entry of visibleEntries) {
1005
+ const { component, options } = entry;
1006
+ // Get layout with height=0 first to determine width and maxHeight
1007
+ // (width and maxHeight don't depend on overlay height)
1008
+ const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
1009
+ // Render component at calculated width
1010
+ let overlayLines = component.render(width);
1011
+ // Apply maxHeight if specified
1012
+ if (maxHeight !== undefined && overlayLines.length > maxHeight) {
1013
+ overlayLines = overlayLines.slice(0, maxHeight);
1014
+ }
1015
+ // Get final row/col with actual overlay height
1016
+ const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
1017
+ entry.bounds = { row, col, width, height: overlayLines.length };
1018
+ rendered.push({ entry, overlayLines, row, col, w: width });
1019
+ minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
1020
+ }
1021
+ this.renderedOverlayLayouts = rendered.map(({ entry, row, col, w, overlayLines }) => ({
1022
+ entry,
1023
+ row,
1024
+ col,
1025
+ width: w,
1026
+ height: overlayLines.length,
1027
+ }));
1028
+ // Pad to at least terminal height so overlays have screen-relative positions.
1029
+ // Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing
1030
+ // inflation that pushed content into scrollback on terminal widen.
1031
+ const workingHeight = Math.max(result.length, termHeight, minLinesNeeded);
1032
+ // Extend result with empty lines if content is too short for overlay placement or working area
1033
+ while (result.length < workingHeight) {
1034
+ result.push("");
1035
+ }
1036
+ const viewportStart = Math.max(0, workingHeight - termHeight);
1037
+ // Composite each overlay
1038
+ for (const { overlayLines, row, col, w } of rendered) {
1039
+ for (let i = 0; i < overlayLines.length; i++) {
1040
+ const idx = viewportStart + row + i;
1041
+ if (idx >= 0 && idx < result.length) {
1042
+ // Defensive: truncate overlay line to declared width before compositing
1043
+ // (components should already respect width, but this ensures it)
1044
+ const truncatedOverlayLine = visibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];
1045
+ result[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
1046
+ }
1047
+ }
1048
+ }
1049
+ return result;
1050
+ }
1051
+ applyLineResets(lines) {
1052
+ const reset = SEGMENT_RESET;
1053
+ for (let i = 0; i < lines.length; i++) {
1054
+ const line = lines[i];
1055
+ if (!isImageLine(line)) {
1056
+ lines[i] = normalizeTerminalOutput(line) + reset;
1057
+ }
1058
+ }
1059
+ return lines;
1060
+ }
1061
+ compositeLineAt(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
1062
+ return compositeTuiLine(baseLine, overlayLine, startCol, overlayWidth, totalWidth);
1063
+ }
1064
+ /**
1065
+ * Find and extract cursor position from rendered lines.
1066
+ * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
1067
+ * Only scans the bottom terminal height lines (visible viewport).
1068
+ * @param lines - Rendered lines to search
1069
+ * @param height - Terminal height (visible viewport size)
1070
+ * @returns Cursor position { row, col } or null if no marker found
1071
+ */
1072
+ extractCursorPosition(lines, height) {
1073
+ // Only scan the bottom `height` lines (visible viewport)
1074
+ const viewportTop = Math.max(0, lines.length - height);
1075
+ for (let row = lines.length - 1; row >= viewportTop; row--) {
1076
+ const line = lines[row];
1077
+ const markerIndex = line.indexOf(CURSOR_MARKER);
1078
+ if (markerIndex !== -1) {
1079
+ // Calculate visual column (width of text before marker)
1080
+ const beforeMarker = line.slice(0, markerIndex);
1081
+ const col = visibleWidth(beforeMarker);
1082
+ // Strip marker from the line
1083
+ lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
1084
+ return { row, col };
1085
+ }
1086
+ }
1087
+ return null;
1088
+ }
1089
+ /**
1090
+ * Query the terminal's default background color with OSC 11 (`ESC ] 11 ; ? BEL`).
1091
+ * @param timeoutMs Query timeout in milliseconds.
1092
+ * @returns Promise containing the parsed RGB color, or undefined if it times out or fails to parse.
1093
+ */
1094
+ queryTerminalBackgroundColor({ timeoutMs }) {
1095
+ return new Promise((resolve) => {
1096
+ const query = {
1097
+ settled: false,
1098
+ resolve,
1099
+ timer: undefined,
1100
+ };
1101
+ query.timer = setTimeout(() => {
1102
+ if (query.settled) {
1103
+ return;
1104
+ }
1105
+ query.settled = true;
1106
+ query.timer = undefined;
1107
+ query.resolve?.(undefined);
1108
+ query.resolve = undefined;
1109
+ }, timeoutMs);
1110
+ this.pendingOsc11BackgroundQueries.push(query);
1111
+ this.pendingOsc11BackgroundReplies += 1;
1112
+ this.terminal.write("\x1b]11;?\x07");
1113
+ });
1114
+ }
1115
+ /**
1116
+ * Query the terminal's color-scheme preference with DSR (`CSI ? 996 n`).
1117
+ * Terminals that support the color palette notification protocol reply with
1118
+ * `CSI ? 997 ; 1 n` for dark or `CSI ? 997 ; 2 n` for light.
1119
+ */
1120
+ queryTerminalColorScheme({ timeoutMs }) {
1121
+ return new Promise((resolve) => {
1122
+ let settled = false;
1123
+ let timer;
1124
+ let unsubscribe = () => { };
1125
+ const settle = (scheme) => {
1126
+ if (settled)
1127
+ return;
1128
+ settled = true;
1129
+ if (timer) {
1130
+ clearTimeout(timer);
1131
+ timer = undefined;
1132
+ }
1133
+ unsubscribe();
1134
+ resolve(scheme);
1135
+ };
1136
+ unsubscribe = this.onTerminalColorSchemeChange(settle);
1137
+ timer = setTimeout(() => settle(undefined), timeoutMs);
1138
+ this.terminal.write("\x1b[?996n");
1139
+ });
1140
+ }
1141
+ }
1142
+ //# sourceMappingURL=tui.js.map