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