@schovest/pi-tui 0.7.3
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.
- package/README.md +791 -0
- package/dist/autocomplete.d.ts +57 -0
- package/dist/autocomplete.d.ts.map +1 -0
- package/dist/autocomplete.js +646 -0
- package/dist/autocomplete.js.map +1 -0
- package/dist/components/box.d.ts +22 -0
- package/dist/components/box.d.ts.map +1 -0
- package/dist/components/box.js +104 -0
- package/dist/components/box.js.map +1 -0
- package/dist/components/cancellable-loader.d.ts +22 -0
- package/dist/components/cancellable-loader.d.ts.map +1 -0
- package/dist/components/cancellable-loader.js +35 -0
- package/dist/components/cancellable-loader.js.map +1 -0
- package/dist/components/editor.d.ts +254 -0
- package/dist/components/editor.d.ts.map +1 -0
- package/dist/components/editor.js +1916 -0
- package/dist/components/editor.js.map +1 -0
- package/dist/components/image.d.ts +28 -0
- package/dist/components/image.d.ts.map +1 -0
- package/dist/components/image.js +89 -0
- package/dist/components/image.js.map +1 -0
- package/dist/components/input.d.ts +37 -0
- package/dist/components/input.d.ts.map +1 -0
- package/dist/components/input.js +385 -0
- package/dist/components/input.js.map +1 -0
- package/dist/components/loader.d.ts +31 -0
- package/dist/components/loader.d.ts.map +1 -0
- package/dist/components/loader.js +69 -0
- package/dist/components/loader.js.map +1 -0
- package/dist/components/markdown.d.ts +96 -0
- package/dist/components/markdown.d.ts.map +1 -0
- package/dist/components/markdown.js +648 -0
- package/dist/components/markdown.js.map +1 -0
- package/dist/components/select-list.d.ts +50 -0
- package/dist/components/select-list.d.ts.map +1 -0
- package/dist/components/select-list.js +161 -0
- package/dist/components/select-list.js.map +1 -0
- package/dist/components/settings-list.d.ts +50 -0
- package/dist/components/settings-list.d.ts.map +1 -0
- package/dist/components/settings-list.js +186 -0
- package/dist/components/settings-list.js.map +1 -0
- package/dist/components/spacer.d.ts +12 -0
- package/dist/components/spacer.d.ts.map +1 -0
- package/dist/components/spacer.js +23 -0
- package/dist/components/spacer.js.map +1 -0
- package/dist/components/text.d.ts +19 -0
- package/dist/components/text.d.ts.map +1 -0
- package/dist/components/text.js +89 -0
- package/dist/components/text.js.map +1 -0
- package/dist/components/truncated-text.d.ts +13 -0
- package/dist/components/truncated-text.d.ts.map +1 -0
- package/dist/components/truncated-text.js +51 -0
- package/dist/components/truncated-text.js.map +1 -0
- package/dist/editor-component.d.ts +39 -0
- package/dist/editor-component.d.ts.map +1 -0
- package/dist/editor-component.js +2 -0
- package/dist/editor-component.js.map +1 -0
- package/dist/fuzzy.d.ts +16 -0
- package/dist/fuzzy.d.ts.map +1 -0
- package/dist/fuzzy.js +110 -0
- package/dist/fuzzy.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -0
- package/dist/keybindings.d.ts +193 -0
- package/dist/keybindings.d.ts.map +1 -0
- package/dist/keybindings.js +174 -0
- package/dist/keybindings.js.map +1 -0
- package/dist/keys.d.ts +184 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/keys.js +1181 -0
- package/dist/keys.js.map +1 -0
- package/dist/kill-ring.d.ts +28 -0
- package/dist/kill-ring.d.ts.map +1 -0
- package/dist/kill-ring.js +44 -0
- package/dist/kill-ring.js.map +1 -0
- package/dist/native-modifiers.d.ts +3 -0
- package/dist/native-modifiers.d.ts.map +1 -0
- package/dist/native-modifiers.js +53 -0
- package/dist/native-modifiers.js.map +1 -0
- package/dist/stdin-buffer.d.ts +60 -0
- package/dist/stdin-buffer.d.ts.map +1 -0
- package/dist/stdin-buffer.js +406 -0
- package/dist/stdin-buffer.js.map +1 -0
- package/dist/terminal-image.d.ts +90 -0
- package/dist/terminal-image.d.ts.map +1 -0
- package/dist/terminal-image.js +366 -0
- package/dist/terminal-image.js.map +1 -0
- package/dist/terminal.d.ts +121 -0
- package/dist/terminal.d.ts.map +1 -0
- package/dist/terminal.js +464 -0
- package/dist/terminal.js.map +1 -0
- package/dist/tui.d.ts +347 -0
- package/dist/tui.d.ts.map +1 -0
- package/dist/tui.js +1608 -0
- package/dist/tui.js.map +1 -0
- package/dist/undo-stack.d.ts +17 -0
- package/dist/undo-stack.d.ts.map +1 -0
- package/dist/undo-stack.js +25 -0
- package/dist/undo-stack.js.map +1 -0
- package/dist/utils.d.ts +101 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +1108 -0
- package/dist/utils.js.map +1 -0
- package/dist/word-navigation.d.ts +25 -0
- package/dist/word-navigation.d.ts.map +1 -0
- package/dist/word-navigation.js +96 -0
- package/dist/word-navigation.js.map +1 -0
- package/native/darwin/prebuilds/darwin-arm64/darwin-modifiers.node +0 -0
- package/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
- package/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
- package/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
- package/package.json +47 -0
package/dist/tui.d.ts
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal TUI implementation with differential rendering
|
|
3
|
+
*/
|
|
4
|
+
import type { MouseEvent } from "./stdin-buffer.ts";
|
|
5
|
+
import type { Terminal } from "./terminal.ts";
|
|
6
|
+
import { visibleWidth } from "./utils.ts";
|
|
7
|
+
/**
|
|
8
|
+
* Component interface - all components must implement this
|
|
9
|
+
*/
|
|
10
|
+
export interface Component {
|
|
11
|
+
/**
|
|
12
|
+
* Render the component to lines for the given viewport width
|
|
13
|
+
* @param width - Current viewport width
|
|
14
|
+
* @returns Array of strings, each representing a line
|
|
15
|
+
*/
|
|
16
|
+
render(width: number): string[];
|
|
17
|
+
/**
|
|
18
|
+
* Optional handler for keyboard input when component has focus.
|
|
19
|
+
* Return true to indicate the input was consumed and should not be processed further.
|
|
20
|
+
* Return void or false to allow TUI to handle the input as a fallback.
|
|
21
|
+
*/
|
|
22
|
+
handleInput?(data: string): boolean | void;
|
|
23
|
+
/**
|
|
24
|
+
* If true, component receives key release events (Kitty protocol).
|
|
25
|
+
* Default is false - release events are filtered out.
|
|
26
|
+
*/
|
|
27
|
+
wantsKeyRelease?: boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Invalidate any cached rendering state.
|
|
30
|
+
* Called when theme changes or when component needs to re-render from scratch.
|
|
31
|
+
*/
|
|
32
|
+
invalidate(): void;
|
|
33
|
+
}
|
|
34
|
+
type InputListenerResult = {
|
|
35
|
+
consume?: boolean;
|
|
36
|
+
data?: string;
|
|
37
|
+
} | undefined;
|
|
38
|
+
type InputListener = (data: string) => InputListenerResult;
|
|
39
|
+
/**
|
|
40
|
+
* Interface for components that can receive focus and display a hardware cursor.
|
|
41
|
+
* When focused, the component should emit CURSOR_MARKER at the cursor position
|
|
42
|
+
* in its render output. TUI will find this marker and position the hardware
|
|
43
|
+
* cursor there for proper IME candidate window positioning.
|
|
44
|
+
*/
|
|
45
|
+
export interface Focusable {
|
|
46
|
+
/** Set by TUI when focus changes. Component should emit CURSOR_MARKER when true. */
|
|
47
|
+
focused: boolean;
|
|
48
|
+
}
|
|
49
|
+
/** Type guard to check if a component implements Focusable */
|
|
50
|
+
export declare function isFocusable(component: Component | null): component is Component & Focusable;
|
|
51
|
+
/**
|
|
52
|
+
* Cursor position marker - APC (Application Program Command) sequence.
|
|
53
|
+
* This is a zero-width escape sequence that terminals ignore.
|
|
54
|
+
* Components emit this at the cursor position when focused.
|
|
55
|
+
* TUI finds and strips this marker, then positions the hardware cursor there.
|
|
56
|
+
*/
|
|
57
|
+
export declare const CURSOR_MARKER = "\u001B_pi:c\u0007";
|
|
58
|
+
export { visibleWidth };
|
|
59
|
+
export interface SelectionState {
|
|
60
|
+
active: boolean;
|
|
61
|
+
anchorRow: number;
|
|
62
|
+
anchorCol: number;
|
|
63
|
+
focusRow: number;
|
|
64
|
+
focusCol: number;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Anchor position for overlays
|
|
68
|
+
*/
|
|
69
|
+
export type OverlayAnchor = "center" | "top-left" | "top-right" | "bottom-left" | "bottom-right" | "top-center" | "bottom-center" | "left-center" | "right-center";
|
|
70
|
+
/**
|
|
71
|
+
* Margin configuration for overlays
|
|
72
|
+
*/
|
|
73
|
+
export interface OverlayMargin {
|
|
74
|
+
top?: number;
|
|
75
|
+
right?: number;
|
|
76
|
+
bottom?: number;
|
|
77
|
+
left?: number;
|
|
78
|
+
}
|
|
79
|
+
/** Value that can be absolute (number) or percentage (string like "50%") */
|
|
80
|
+
export type SizeValue = number | `${number}%`;
|
|
81
|
+
/**
|
|
82
|
+
* Options for overlay positioning and sizing.
|
|
83
|
+
* Values can be absolute numbers or percentage strings (e.g., "50%").
|
|
84
|
+
*/
|
|
85
|
+
export interface OverlayOptions {
|
|
86
|
+
/** Width in columns, or percentage of terminal width (e.g., "50%") */
|
|
87
|
+
width?: SizeValue;
|
|
88
|
+
/** Minimum width in columns */
|
|
89
|
+
minWidth?: number;
|
|
90
|
+
/** Maximum height in rows, or percentage of terminal height (e.g., "50%") */
|
|
91
|
+
maxHeight?: SizeValue;
|
|
92
|
+
/** Anchor point for positioning (default: 'center') */
|
|
93
|
+
anchor?: OverlayAnchor;
|
|
94
|
+
/** Horizontal offset from anchor position (positive = right) */
|
|
95
|
+
offsetX?: number;
|
|
96
|
+
/** Vertical offset from anchor position (positive = down) */
|
|
97
|
+
offsetY?: number;
|
|
98
|
+
/** Row position: absolute number, or percentage (e.g., "25%" = 25% from top) */
|
|
99
|
+
row?: SizeValue;
|
|
100
|
+
/** Column position: absolute number, or percentage (e.g., "50%" = centered horizontally) */
|
|
101
|
+
col?: SizeValue;
|
|
102
|
+
/** Margin from terminal edges. Number applies to all sides. */
|
|
103
|
+
margin?: OverlayMargin | number;
|
|
104
|
+
/**
|
|
105
|
+
* Control overlay visibility based on terminal dimensions.
|
|
106
|
+
* If provided, overlay is only rendered when this returns true.
|
|
107
|
+
* Called each render cycle with current terminal dimensions.
|
|
108
|
+
*/
|
|
109
|
+
visible?: (termWidth: number, termHeight: number) => boolean;
|
|
110
|
+
/** If true, don't capture keyboard focus when shown */
|
|
111
|
+
nonCapturing?: boolean;
|
|
112
|
+
/** ANSI background sequence to fill behind overlay lines (e.g., "\x1b[48;5;235m") */
|
|
113
|
+
background?: string;
|
|
114
|
+
/**
|
|
115
|
+
* Restrict text selection (copy/highlight) to a specific column region within the overlay.
|
|
116
|
+
* Called per screen row during selection extraction and highlight rendering.
|
|
117
|
+
* Returns `{ col, width }` for the selectable region, or null to allow the full row.
|
|
118
|
+
* This is used by overlays with internal column splits (e.g., left list + right detail)
|
|
119
|
+
* to prevent the non-detail sidebar from being included in copy/highlight operations.
|
|
120
|
+
*/
|
|
121
|
+
selectionClip?: (screenRow: number) => {
|
|
122
|
+
col: number;
|
|
123
|
+
width: number;
|
|
124
|
+
} | null;
|
|
125
|
+
}
|
|
126
|
+
/** Options for {@link OverlayHandle.unfocus}. */
|
|
127
|
+
export interface OverlayUnfocusOptions {
|
|
128
|
+
/** Explicit target to focus after releasing this overlay. */
|
|
129
|
+
target: Component | null;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Handle returned by showOverlay for controlling the overlay
|
|
133
|
+
*/
|
|
134
|
+
export interface OverlayHandle {
|
|
135
|
+
/** Permanently remove the overlay (cannot be shown again) */
|
|
136
|
+
hide(): void;
|
|
137
|
+
/** Temporarily hide or show the overlay */
|
|
138
|
+
setHidden(hidden: boolean): void;
|
|
139
|
+
/** Check if overlay is temporarily hidden */
|
|
140
|
+
isHidden(): boolean;
|
|
141
|
+
/** Focus this overlay and bring it to the visual front */
|
|
142
|
+
focus(): void;
|
|
143
|
+
/** Release focus to the next visible capturing overlay or previous target, or to an explicit target when provided */
|
|
144
|
+
unfocus(options?: OverlayUnfocusOptions): void;
|
|
145
|
+
/** Check if this overlay currently has focus */
|
|
146
|
+
isFocused(): boolean;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Container - a component that contains other components
|
|
150
|
+
*/
|
|
151
|
+
export declare class Container implements Component {
|
|
152
|
+
children: Component[];
|
|
153
|
+
addChild(component: Component): void;
|
|
154
|
+
removeChild(component: Component): void;
|
|
155
|
+
clear(): void;
|
|
156
|
+
invalidate(): void;
|
|
157
|
+
render(width: number): string[];
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* TUI - Main class for managing terminal UI with differential rendering
|
|
161
|
+
*/
|
|
162
|
+
export declare class TUI extends Container {
|
|
163
|
+
terminal: Terminal;
|
|
164
|
+
private previousLines;
|
|
165
|
+
private previousKittyImageIds;
|
|
166
|
+
private previousWidth;
|
|
167
|
+
private previousHeight;
|
|
168
|
+
private focusedComponent;
|
|
169
|
+
private inputListeners;
|
|
170
|
+
/** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
|
|
171
|
+
onDebug?: () => void;
|
|
172
|
+
private renderRequested;
|
|
173
|
+
private renderTimer;
|
|
174
|
+
private lastRenderAt;
|
|
175
|
+
private static readonly MIN_RENDER_INTERVAL_MS;
|
|
176
|
+
private cursorRow;
|
|
177
|
+
private hardwareCursorRow;
|
|
178
|
+
private showHardwareCursor;
|
|
179
|
+
private clearOnShrink;
|
|
180
|
+
private maxLinesRendered;
|
|
181
|
+
private previousViewportTop;
|
|
182
|
+
private fullRedrawCount;
|
|
183
|
+
private stopped;
|
|
184
|
+
private fixedBottomCount;
|
|
185
|
+
private currentScrollableViewportTop;
|
|
186
|
+
private currentFullLines;
|
|
187
|
+
private currentCompositedLines;
|
|
188
|
+
private currentScrollableLinesLength;
|
|
189
|
+
private autoScrollDirection;
|
|
190
|
+
private selection;
|
|
191
|
+
private scrollOffset;
|
|
192
|
+
private autoFollow;
|
|
193
|
+
private previousScrollableLineCount;
|
|
194
|
+
private lastScrollableViewport;
|
|
195
|
+
private autoScrollTimer;
|
|
196
|
+
private mouseListenerRemover?;
|
|
197
|
+
private renderedOverlayLayouts;
|
|
198
|
+
private pendingScrollDelta;
|
|
199
|
+
private scrollDebounceTimer;
|
|
200
|
+
private static readonly SCROLL_DEBOUNCE_MS;
|
|
201
|
+
private lastMouseWheelTime;
|
|
202
|
+
private static readonly MOUSE_WHEEL_SUPPRESS_MS;
|
|
203
|
+
onCopySelection?: (text: string) => void;
|
|
204
|
+
onScrollOffsetChange?: (offset: number) => void;
|
|
205
|
+
private focusOrderCounter;
|
|
206
|
+
private overlayStack;
|
|
207
|
+
private overlayFocusRestore;
|
|
208
|
+
constructor(terminal: Terminal, showHardwareCursor?: boolean);
|
|
209
|
+
get fullRedraws(): number;
|
|
210
|
+
getShowHardwareCursor(): boolean;
|
|
211
|
+
setShowHardwareCursor(enabled: boolean): void;
|
|
212
|
+
getClearOnShrink(): boolean;
|
|
213
|
+
/**
|
|
214
|
+
* Set whether to trigger full re-render when content shrinks.
|
|
215
|
+
* When true (default), empty rows are cleared when content shrinks.
|
|
216
|
+
* When false, empty rows remain (reduces redraws on slower terminals).
|
|
217
|
+
*/
|
|
218
|
+
setClearOnShrink(enabled: boolean): void;
|
|
219
|
+
setFocus(component: Component | null): void;
|
|
220
|
+
private setFocusInternal;
|
|
221
|
+
private clearOverlayFocusRestore;
|
|
222
|
+
private clearOverlayFocusRestoreFor;
|
|
223
|
+
private resolveBlockedOverlayFocusResume;
|
|
224
|
+
private getVisibleOverlayFocusRestore;
|
|
225
|
+
private isOverlayFocusAncestor;
|
|
226
|
+
private retargetOverlayPreFocus;
|
|
227
|
+
private isComponentMounted;
|
|
228
|
+
private containsComponent;
|
|
229
|
+
/**
|
|
230
|
+
* Show an overlay component with configurable positioning and sizing.
|
|
231
|
+
* Returns a handle to control the overlay's visibility.
|
|
232
|
+
*/
|
|
233
|
+
showOverlay(component: Component, options?: OverlayOptions): OverlayHandle;
|
|
234
|
+
/** Hide the topmost overlay and restore previous focus. */
|
|
235
|
+
hideOverlay(): void;
|
|
236
|
+
/** Check if there are any visible overlays */
|
|
237
|
+
hasOverlay(): boolean;
|
|
238
|
+
/** Check if an overlay entry is currently visible */
|
|
239
|
+
private isOverlayVisible;
|
|
240
|
+
/** Find the visual-frontmost visible capturing overlay, if any */
|
|
241
|
+
private getTopmostVisibleOverlay;
|
|
242
|
+
invalidate(): void;
|
|
243
|
+
start(): void;
|
|
244
|
+
addInputListener(listener: InputListener): () => void;
|
|
245
|
+
removeInputListener(listener: InputListener): void;
|
|
246
|
+
private queryCellSize;
|
|
247
|
+
stop(): void;
|
|
248
|
+
private setupMouseListener;
|
|
249
|
+
private removeMouseListener;
|
|
250
|
+
handleMouseEvent(event: MouseEvent): void;
|
|
251
|
+
private getMaxScrollOffset;
|
|
252
|
+
/** Flush pending scroll delta and trigger a single render */
|
|
253
|
+
private flushPendingScroll;
|
|
254
|
+
getScrollOffset(): number;
|
|
255
|
+
setScrollOffset(offset: number): void;
|
|
256
|
+
resetScrollOffset(): void;
|
|
257
|
+
getAutoFollow(): boolean;
|
|
258
|
+
setAutoFollow(value: boolean): void;
|
|
259
|
+
setFixedBottomCount(count: number): void;
|
|
260
|
+
private startAutoScroll;
|
|
261
|
+
private clearAutoScrollTimer;
|
|
262
|
+
/**
|
|
263
|
+
* Clear the current selection and stop any active autoScroll.
|
|
264
|
+
* Called by overlays when their internal scroll changes, to prevent
|
|
265
|
+
* stale selection highlighting on shifted content.
|
|
266
|
+
*/
|
|
267
|
+
clearSelection(): void;
|
|
268
|
+
private extractSelectionText;
|
|
269
|
+
/**
|
|
270
|
+
* Get the selection clip region for a given screen row.
|
|
271
|
+
* If any overlay with a selectionClip callback covers this row,
|
|
272
|
+
* returns the clip region to restrict selection to that area.
|
|
273
|
+
*/
|
|
274
|
+
private getSelectionClipForRow;
|
|
275
|
+
/**
|
|
276
|
+
* Convert a screen row (0-indexed terminal row) to a buffer-absolute row index
|
|
277
|
+
* in `this.currentFullLines`. Used by mouseDown/mouseMove to set selection
|
|
278
|
+
* anchor/focus in stable buffer coordinates that survive scrolling.
|
|
279
|
+
*
|
|
280
|
+
* - Screen rows in the scrollable area map to:
|
|
281
|
+
* currentScrollableViewportTop + screenRow
|
|
282
|
+
* - Screen rows in the fixed area map to:
|
|
283
|
+
* currentScrollableLinesLength + (screenRow - lastScrollableViewport)
|
|
284
|
+
*/
|
|
285
|
+
private screenToBufferRow;
|
|
286
|
+
/**
|
|
287
|
+
* Convert a buffer-absolute row index back to a screen row.
|
|
288
|
+
* Returns -1 if the buffer row is a scrollable line currently outside the viewport.
|
|
289
|
+
* Fixed-area buffer rows always map to a visible screen row.
|
|
290
|
+
*/
|
|
291
|
+
private bufferToScreenRow;
|
|
292
|
+
private applySelectionHighlight;
|
|
293
|
+
requestRender(force?: boolean): void;
|
|
294
|
+
private scheduleRender;
|
|
295
|
+
private handleInput;
|
|
296
|
+
private consumeCellSizeResponse;
|
|
297
|
+
/**
|
|
298
|
+
* Resolve overlay layout from options.
|
|
299
|
+
* Returns { width, row, col, maxHeight } for rendering.
|
|
300
|
+
*/
|
|
301
|
+
private resolveOverlayLayout;
|
|
302
|
+
private resolveAnchorRow;
|
|
303
|
+
private resolveAnchorCol;
|
|
304
|
+
/** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
|
|
305
|
+
private compositeOverlays;
|
|
306
|
+
private static readonly SEGMENT_RESET;
|
|
307
|
+
private applyLineResets;
|
|
308
|
+
private collectKittyImageIds;
|
|
309
|
+
private deleteKittyImages;
|
|
310
|
+
private expandLastChangedForKittyImages;
|
|
311
|
+
private deleteChangedKittyImages;
|
|
312
|
+
/** Apply background fill to the overlay region of a base line. */
|
|
313
|
+
private applyOverlayBackground;
|
|
314
|
+
/** Splice overlay content into a base line at a specific column. Single-pass optimized. */
|
|
315
|
+
private compositeLineAt;
|
|
316
|
+
/**
|
|
317
|
+
* Find and extract cursor position from rendered lines.
|
|
318
|
+
* Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
|
|
319
|
+
* Only scans the bottom terminal height lines (visible viewport).
|
|
320
|
+
* @param lines - Rendered lines to search
|
|
321
|
+
* @param height - Terminal height (visible viewport size)
|
|
322
|
+
* @returns Cursor position { row, col } or null if no marker found
|
|
323
|
+
*/
|
|
324
|
+
private extractCursorPosition;
|
|
325
|
+
private renderingSuspended;
|
|
326
|
+
suspendRendering(): void;
|
|
327
|
+
resumeRendering(): void;
|
|
328
|
+
private doRender;
|
|
329
|
+
/**
|
|
330
|
+
* Build escape sequences for positioning the hardware cursor.
|
|
331
|
+
* Returned string should be appended to the render buffer *before*
|
|
332
|
+
* the sync-mode terminator (\x1b[?2026l) so the cursor state change
|
|
333
|
+
* is atomic with the content update and never causes a visible flash.
|
|
334
|
+
* @param cursorPos The cursor position extracted from rendered output, or null
|
|
335
|
+
* @param totalLines Total number of rendered lines
|
|
336
|
+
*/
|
|
337
|
+
private buildHardwareCursorSequence;
|
|
338
|
+
/**
|
|
339
|
+
* Cursor-hide prefix to place at the start of every render buffer,
|
|
340
|
+
* before any content updates. Guarantees the hardware cursor is
|
|
341
|
+
* invisible before the terminal processes line changes, which
|
|
342
|
+
* prevents the cursor from briefly appearing at stale positions
|
|
343
|
+
* on terminals with imperfect sync-mode support.
|
|
344
|
+
*/
|
|
345
|
+
private static readonly CURSOR_HIDE_PREFIX;
|
|
346
|
+
}
|
|
347
|
+
//# sourceMappingURL=tui.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tui.d.ts","sourceRoot":"","sources":["../src/tui.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * Minimal TUI implementation with differential rendering\n */\n\nimport { performance } from \"node:perf_hooks\";\nimport { isKeyRelease, matchesKey } from \"./keys.ts\";\nimport type { MouseEvent } from \"./stdin-buffer.ts\";\nimport type { Terminal } from \"./terminal.ts\";\nimport { deleteKittyImage, getCapabilities, isImageLine, setCellDimensions } from \"./terminal-image.ts\";\nimport {\n\textractSegments,\n\tnormalizeTerminalOutput,\n\tsliceByColumn,\n\tsliceWithWidth,\n\tsnapColToGraphemeBoundary,\n\tstripAnsi,\n\tvisibleWidth,\n} from \"./utils.ts\";\n\nconst KITTY_SEQUENCE_PREFIX = \"\\x1b_G\";\n\nfunction extractKittyImageIds(line: string): number[] {\n\tconst sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);\n\tif (sequenceStart === -1) return [];\n\n\tconst paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;\n\tconst paramsEnd = line.indexOf(\";\", paramsStart);\n\tif (paramsEnd === -1) return [];\n\n\tconst params = line.slice(paramsStart, paramsEnd);\n\tfor (const param of params.split(\",\")) {\n\t\tconst [key, value] = param.split(\"=\", 2);\n\t\tif (key !== \"i\" || value === undefined) continue;\n\t\tconst id = Number(value);\n\t\tif (Number.isInteger(id) && id > 0 && id <= 0xffffffff) {\n\t\t\treturn [id];\n\t\t}\n\t}\n\treturn [];\n}\n\n/**\n * Component interface - all components must implement this\n */\nexport interface Component {\n\t/**\n\t * Render the component to lines for the given viewport width\n\t * @param width - Current viewport width\n\t * @returns Array of strings, each representing a line\n\t */\n\trender(width: number): string[];\n\n\t/**\n\t * Optional handler for keyboard input when component has focus.\n\t * Return true to indicate the input was consumed and should not be processed further.\n\t * Return void or false to allow TUI to handle the input as a fallback.\n\t */\n\t// biome-ignore lint/suspicious/noConfusingVoidType: void is intentional - implementations may return nothing or boolean\n\thandleInput?(data: string): boolean | void;\n\n\t/**\n\t * If true, component receives key release events (Kitty protocol).\n\t * Default is false - release events are filtered out.\n\t */\n\twantsKeyRelease?: boolean;\n\n\t/**\n\t * Invalidate any cached rendering state.\n\t * Called when theme changes or when component needs to re-render from scratch.\n\t */\n\tinvalidate(): void;\n}\n\ntype InputListenerResult = { consume?: boolean; data?: string } | undefined;\ntype InputListener = (data: string) => InputListenerResult;\n\n/**\n * Interface for components that can receive focus and display a hardware cursor.\n * When focused, the component should emit CURSOR_MARKER at the cursor position\n * in its render output. TUI will find this marker and position the hardware\n * cursor there for proper IME candidate window positioning.\n */\nexport interface Focusable {\n\t/** Set by TUI when focus changes. Component should emit CURSOR_MARKER when true. */\n\tfocused: boolean;\n}\n\n/** Type guard to check if a component implements Focusable */\nexport function isFocusable(component: Component | null): component is Component & Focusable {\n\treturn component !== null && \"focused\" in component;\n}\n\n/**\n * Cursor position marker - APC (Application Program Command) sequence.\n * This is a zero-width escape sequence that terminals ignore.\n * Components emit this at the cursor position when focused.\n * TUI finds and strips this marker, then positions the hardware cursor there.\n */\nexport const CURSOR_MARKER = \"\\x1b_pi:c\\x07\";\n\nexport { visibleWidth };\n\nexport interface SelectionState {\n\tactive: boolean;\n\tanchorRow: number;\n\tanchorCol: number;\n\tfocusRow: number;\n\tfocusCol: number;\n}\n\nconst AUTO_SCROLL_INTERVAL_MS = 100;\nconst AUTO_SCROLL_ROWS = 3;\n\n/**\n * Anchor position for overlays\n */\nexport type OverlayAnchor =\n\t| \"center\"\n\t| \"top-left\"\n\t| \"top-right\"\n\t| \"bottom-left\"\n\t| \"bottom-right\"\n\t| \"top-center\"\n\t| \"bottom-center\"\n\t| \"left-center\"\n\t| \"right-center\";\n\n/**\n * Margin configuration for overlays\n */\nexport interface OverlayMargin {\n\ttop?: number;\n\tright?: number;\n\tbottom?: number;\n\tleft?: number;\n}\n\n/** Value that can be absolute (number) or percentage (string like \"50%\") */\nexport type SizeValue = number | `${number}%`;\n\n/** Parse a SizeValue into absolute value given a reference size */\nfunction parseSizeValue(value: SizeValue | undefined, referenceSize: number): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (typeof value === \"number\") return value;\n\t// Parse percentage string like \"50%\"\n\tconst match = value.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\tif (match) {\n\t\treturn Math.floor((referenceSize * parseFloat(match[1])) / 100);\n\t}\n\treturn undefined;\n}\n\nfunction isTermuxSession(): boolean {\n\treturn Boolean(process.env.TERMUX_VERSION);\n}\n\n/**\n * Options for overlay positioning and sizing.\n * Values can be absolute numbers or percentage strings (e.g., \"50%\").\n */\nexport interface OverlayOptions {\n\t// === Sizing ===\n\t/** Width in columns, or percentage of terminal width (e.g., \"50%\") */\n\twidth?: SizeValue;\n\t/** Minimum width in columns */\n\tminWidth?: number;\n\t/** Maximum height in rows, or percentage of terminal height (e.g., \"50%\") */\n\tmaxHeight?: SizeValue;\n\n\t// === Positioning - anchor-based ===\n\t/** Anchor point for positioning (default: 'center') */\n\tanchor?: OverlayAnchor;\n\t/** Horizontal offset from anchor position (positive = right) */\n\toffsetX?: number;\n\t/** Vertical offset from anchor position (positive = down) */\n\toffsetY?: number;\n\n\t// === Positioning - percentage or absolute ===\n\t/** Row position: absolute number, or percentage (e.g., \"25%\" = 25% from top) */\n\trow?: SizeValue;\n\t/** Column position: absolute number, or percentage (e.g., \"50%\" = centered horizontally) */\n\tcol?: SizeValue;\n\n\t// === Margin from terminal edges ===\n\t/** Margin from terminal edges. Number applies to all sides. */\n\tmargin?: OverlayMargin | number;\n\n\t// === Visibility ===\n\t/**\n\t * Control overlay visibility based on terminal dimensions.\n\t * If provided, overlay is only rendered when this returns true.\n\t * Called each render cycle with current terminal dimensions.\n\t */\n\tvisible?: (termWidth: number, termHeight: number) => boolean;\n\t/** If true, don't capture keyboard focus when shown */\n\tnonCapturing?: boolean;\n\t/** ANSI background sequence to fill behind overlay lines (e.g., \"\\x1b[48;5;235m\") */\n\tbackground?: string;\n\t/**\n\t * Restrict text selection (copy/highlight) to a specific column region within the overlay.\n\t * Called per screen row during selection extraction and highlight rendering.\n\t * Returns `{ col, width }` for the selectable region, or null to allow the full row.\n\t * This is used by overlays with internal column splits (e.g., left list + right detail)\n\t * to prevent the non-detail sidebar from being included in copy/highlight operations.\n\t */\n\tselectionClip?: (screenRow: number) => { col: number; width: number } | null;\n}\n\n/** Options for {@link OverlayHandle.unfocus}. */\nexport interface OverlayUnfocusOptions {\n\t/** Explicit target to focus after releasing this overlay. */\n\ttarget: Component | null;\n}\n\n/**\n * Handle returned by showOverlay for controlling the overlay\n */\nexport interface OverlayHandle {\n\t/** Permanently remove the overlay (cannot be shown again) */\n\thide(): void;\n\t/** Temporarily hide or show the overlay */\n\tsetHidden(hidden: boolean): void;\n\t/** Check if overlay is temporarily hidden */\n\tisHidden(): boolean;\n\t/** Focus this overlay and bring it to the visual front */\n\tfocus(): void;\n\t/** Release focus to the next visible capturing overlay or previous target, or to an explicit target when provided */\n\tunfocus(options?: OverlayUnfocusOptions): void;\n\t/** Check if this overlay currently has focus */\n\tisFocused(): boolean;\n}\n\ntype OverlayStackEntry = {\n\tcomponent: Component;\n\toptions?: OverlayOptions;\n\tpreFocus: Component | null;\n\thidden: boolean;\n\tfocusOrder: number;\n};\n\ntype OverlayBlockedFocusResume = { status: \"restore-overlay\" } | { status: \"focus-target\"; target: Component | null };\ntype EligibleOverlayFocusRestoreState = { status: \"eligible\"; overlay: OverlayStackEntry };\ntype BlockedOverlayFocusRestoreState = {\n\tstatus: \"blocked\";\n\toverlay: OverlayStackEntry;\n\tblockedBy: Component;\n\tresume: OverlayBlockedFocusResume;\n};\ntype ActiveOverlayFocusRestoreState = EligibleOverlayFocusRestoreState | BlockedOverlayFocusRestoreState;\ntype OverlayFocusRestoreState = { status: \"inactive\" } | ActiveOverlayFocusRestoreState;\ntype OverlayFocusRestorePolicy = \"clear\" | \"preserve\";\n\n/**\n * Container - a component that contains other components\n */\nexport class Container implements Component {\n\tchildren: Component[] = [];\n\n\taddChild(component: Component): void {\n\t\tthis.children.push(component);\n\t}\n\n\tremoveChild(component: Component): void {\n\t\tconst index = this.children.indexOf(component);\n\t\tif (index !== -1) {\n\t\t\tthis.children.splice(index, 1);\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tthis.children = [];\n\t}\n\n\tinvalidate(): void {\n\t\tfor (const child of this.children) {\n\t\t\tchild.invalidate?.();\n\t\t}\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\t\tfor (const child of this.children) {\n\t\t\tconst childLines = child.render(width);\n\t\t\tfor (const line of childLines) {\n\t\t\t\tlines.push(line);\n\t\t\t}\n\t\t}\n\t\treturn lines;\n\t}\n}\n\n/**\n * TUI - Main class for managing terminal UI with differential rendering\n */\nexport class TUI extends Container {\n\tpublic terminal: Terminal;\n\tprivate previousLines: string[] = [];\n\tprivate previousKittyImageIds = new Set<number>();\n\tprivate previousWidth = 0;\n\tprivate previousHeight = 0;\n\tprivate focusedComponent: Component | null = null;\n\tprivate inputListeners = new Set<InputListener>();\n\n\t/** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */\n\tpublic onDebug?: () => void;\n\tprivate renderRequested = false;\n\tprivate renderTimer: NodeJS.Timeout | undefined;\n\tprivate lastRenderAt = 0;\n\tprivate static readonly MIN_RENDER_INTERVAL_MS = 16;\n\t// biome-ignore lint/correctness/noUnusedPrivateClassMembers: used in render and cursor positioning\n\tprivate cursorRow = 0; // Logical cursor row (end of rendered content)\n\tprivate hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)\n\tprivate showHardwareCursor = process.env.PI_HARDWARE_CURSOR !== \"0\";\n\tprivate clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === \"1\"; // Clear empty rows when content shrinks (default: off)\n\tprivate maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)\n\tprivate previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves\n\tprivate fullRedrawCount = 0;\n\tprivate stopped = false;\n\tprivate fixedBottomCount = 0;\n\t// Scrollable viewport top in the full-lines buffer; used for mouse coordinate mapping\n\tprivate currentScrollableViewportTop = 0;\n\t// Full-lines buffer (pre-overlay, pre-highlight) cached each render for selection\n\t// coordinate mapping and text extraction. Equals [...scrollableLines, ...fixedLines].\n\tprivate currentFullLines: string[] = [];\n\t// Overlay-composited lines (post-overlay, pre-highlight) cached each render for text extraction and grapheme snapping when an overlay covers a row\n\tprivate currentCompositedLines: string[] = [];\n\tprivate currentScrollableLinesLength: number = 0;\n\tprivate autoScrollDirection: -1 | 1 = -1;\n\tprivate selection: SelectionState | null = null;\n\tprivate scrollOffset = 0;\n\tprivate autoFollow = true;\n\tprivate previousScrollableLineCount = 0;\n\tprivate lastScrollableViewport = 0;\n\tprivate autoScrollTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate mouseListenerRemover?: () => void;\n\t// Cached overlay layouts from the most recent render, used for selection clip\n\tprivate renderedOverlayLayouts: {\n\t\trow: number;\n\t\tcol: number;\n\t\twidth: number;\n\t\theight: number;\n\t\tselectionClip?: (screenRow: number) => { col: number; width: number } | null;\n\t}[] = [];\n\t// Scroll event debouncing: aggregate consecutive wheel events\n\tprivate pendingScrollDelta = 0;\n\tprivate scrollDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate static readonly SCROLL_DEBOUNCE_MS = 8;\n\t// Timestamp of the last mouse wheel event, used to suppress spurious\n\t// arrow-key sequences that some terminals emit alongside scroll events.\n\tprivate lastMouseWheelTime = 0;\n\tprivate static readonly MOUSE_WHEEL_SUPPRESS_MS = 50;\n\tonCopySelection?: (text: string) => void;\n\tonScrollOffsetChange?: (offset: number) => void;\n\n\t// Overlay stack for modal components rendered on top of base content\n\tprivate focusOrderCounter = 0;\n\tprivate overlayStack: OverlayStackEntry[] = [];\n\tprivate overlayFocusRestore: OverlayFocusRestoreState = { status: \"inactive\" };\n\n\tconstructor(terminal: Terminal, showHardwareCursor?: boolean) {\n\t\tsuper();\n\t\tthis.terminal = terminal;\n\t\tif (showHardwareCursor !== undefined) {\n\t\t\tthis.showHardwareCursor = showHardwareCursor;\n\t\t}\n\t}\n\n\tget fullRedraws(): number {\n\t\treturn this.fullRedrawCount;\n\t}\n\n\tgetShowHardwareCursor(): boolean {\n\t\treturn this.showHardwareCursor;\n\t}\n\n\tsetShowHardwareCursor(enabled: boolean): void {\n\t\tif (this.showHardwareCursor === enabled) return;\n\t\tthis.showHardwareCursor = enabled;\n\t\tif (enabled) {\n\t\t\t// Set steady bar cursor shape when enabling hardware cursor\n\t\t\tthis.terminal.write(\"\\x1b[6 q\");\n\t\t} else {\n\t\t\tthis.terminal.hideCursor();\n\t\t}\n\t\tthis.requestRender();\n\t}\n\n\tgetClearOnShrink(): boolean {\n\t\treturn this.clearOnShrink;\n\t}\n\n\t/**\n\t * Set whether to trigger full re-render when content shrinks.\n\t * When true (default), empty rows are cleared when content shrinks.\n\t * When false, empty rows remain (reduces redraws on slower terminals).\n\t */\n\tsetClearOnShrink(enabled: boolean): void {\n\t\tthis.clearOnShrink = enabled;\n\t}\n\n\tsetFocus(component: Component | null): void {\n\t\tthis.setFocusInternal({ component, overlayFocusRestore: \"clear\" });\n\t}\n\n\tprivate setFocusInternal({\n\t\tcomponent,\n\t\toverlayFocusRestore,\n\t}: {\n\t\tcomponent: Component | null;\n\t\toverlayFocusRestore: OverlayFocusRestorePolicy;\n\t}): void {\n\t\tconst previousFocus = this.focusedComponent;\n\t\tlet nextFocus = component;\n\t\tconst previousFocusedOverlay = previousFocus\n\t\t\t? this.overlayStack.find((entry) => entry.component === previousFocus && this.isOverlayVisible(entry))\n\t\t\t: undefined;\n\t\tconst nextFocusIsOverlay = nextFocus ? this.overlayStack.some((entry) => entry.component === nextFocus) : false;\n\t\tconst restoreState = this.getVisibleOverlayFocusRestore();\n\t\tif (nextFocus && !nextFocusIsOverlay) {\n\t\t\tif (restoreState.status === \"blocked\" && restoreState.blockedBy === previousFocus) {\n\t\t\t\tif (restoreState.resume.status === \"focus-target\" || !this.isComponentMounted(restoreState.blockedBy)) {\n\t\t\t\t\tnextFocus = this.resolveBlockedOverlayFocusResume(restoreState);\n\t\t\t\t} else {\n\t\t\t\t\tthis.overlayFocusRestore = {\n\t\t\t\t\t\tstatus: \"blocked\",\n\t\t\t\t\t\toverlay: restoreState.overlay,\n\t\t\t\t\t\tblockedBy: nextFocus,\n\t\t\t\t\t\tresume: restoreState.resume,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} else if (\n\t\t\t\tpreviousFocusedOverlay &&\n\t\t\t\trestoreState.status !== \"inactive\" &&\n\t\t\t\trestoreState.overlay === previousFocusedOverlay &&\n\t\t\t\t!this.isOverlayFocusAncestor(previousFocusedOverlay, nextFocus)\n\t\t\t) {\n\t\t\t\tthis.overlayFocusRestore = {\n\t\t\t\t\tstatus: \"blocked\",\n\t\t\t\t\toverlay: previousFocusedOverlay,\n\t\t\t\t\tblockedBy: nextFocus,\n\t\t\t\t\tresume: { status: \"restore-overlay\" },\n\t\t\t\t};\n\t\t\t}\n\t\t} else if (nextFocus === null) {\n\t\t\tif (restoreState.status === \"blocked\" && restoreState.blockedBy === previousFocus) {\n\t\t\t\tnextFocus = this.resolveBlockedOverlayFocusResume(restoreState);\n\t\t\t} else if (overlayFocusRestore === \"clear\") {\n\t\t\t\tthis.clearOverlayFocusRestore();\n\t\t\t}\n\t\t}\n\n\t\tif (isFocusable(this.focusedComponent)) {\n\t\t\tthis.focusedComponent.focused = false;\n\t\t}\n\n\t\tthis.focusedComponent = nextFocus;\n\n\t\tif (isFocusable(nextFocus)) {\n\t\t\tnextFocus.focused = true;\n\t\t}\n\n\t\tconst focusedOverlay = nextFocus\n\t\t\t? this.overlayStack.find((entry) => entry.component === nextFocus && this.isOverlayVisible(entry))\n\t\t\t: undefined;\n\t\tif (focusedOverlay) {\n\t\t\tthis.overlayFocusRestore = { status: \"eligible\", overlay: focusedOverlay };\n\t\t}\n\t}\n\n\tprivate clearOverlayFocusRestore(): void {\n\t\tthis.overlayFocusRestore = { status: \"inactive\" };\n\t}\n\n\tprivate clearOverlayFocusRestoreFor(overlay: OverlayStackEntry): void {\n\t\tif (this.overlayFocusRestore.status !== \"inactive\" && this.overlayFocusRestore.overlay === overlay) {\n\t\t\tthis.clearOverlayFocusRestore();\n\t\t}\n\t}\n\n\tprivate resolveBlockedOverlayFocusResume(restoreState: BlockedOverlayFocusRestoreState): Component | null {\n\t\tif (restoreState.resume.status === \"restore-overlay\") return restoreState.overlay.component;\n\t\tthis.clearOverlayFocusRestore();\n\t\treturn restoreState.resume.target;\n\t}\n\n\tprivate getVisibleOverlayFocusRestore(): OverlayFocusRestoreState {\n\t\tconst restoreState = this.overlayFocusRestore;\n\t\tif (restoreState.status === \"inactive\") return restoreState;\n\t\tif (!this.overlayStack.includes(restoreState.overlay) || !this.isOverlayVisible(restoreState.overlay)) {\n\t\t\treturn { status: \"inactive\" };\n\t\t}\n\t\treturn restoreState;\n\t}\n\n\tprivate isOverlayFocusAncestor(entry: OverlayStackEntry, component: Component): boolean {\n\t\tconst visited = new Set<Component>();\n\t\tlet current = entry.preFocus;\n\t\twhile (current && !visited.has(current)) {\n\t\t\tvisited.add(current);\n\t\t\tif (current === component) return true;\n\t\t\tcurrent = this.overlayStack.find((overlay) => overlay.component === current)?.preFocus ?? null;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate retargetOverlayPreFocus(removed: OverlayStackEntry): void {\n\t\tfor (const overlay of this.overlayStack) {\n\t\t\tif (overlay !== removed && overlay.preFocus === removed.component) {\n\t\t\t\toverlay.preFocus = removed.preFocus;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate isComponentMounted(component: Component): boolean {\n\t\treturn this.children.some((child) => this.containsComponent(child, component));\n\t}\n\n\tprivate containsComponent(root: Component, target: Component): boolean {\n\t\tif (root === target) return true;\n\t\tif (!(root instanceof Container)) return false;\n\t\treturn root.children.some((child) => this.containsComponent(child, target));\n\t}\n\n\t/**\n\t * Show an overlay component with configurable positioning and sizing.\n\t * Returns a handle to control the overlay's visibility.\n\t */\n\tshowOverlay(component: Component, options?: OverlayOptions): OverlayHandle {\n\t\tconst entry: OverlayStackEntry = {\n\t\t\tcomponent,\n\t\t\t...(options === undefined ? {} : { options }),\n\t\t\tpreFocus: this.focusedComponent,\n\t\t\thidden: false,\n\t\t\tfocusOrder: ++this.focusOrderCounter,\n\t\t};\n\t\tthis.overlayStack.push(entry);\n\t\t// Only focus if overlay is actually visible\n\t\tif (!options?.nonCapturing && this.isOverlayVisible(entry)) {\n\t\t\tthis.setFocus(component);\n\t\t}\n\t\tif (!this.showHardwareCursor) {\n\t\t\tthis.terminal.hideCursor();\n\t\t}\n\t\tthis.requestRender();\n\n\t\t// Return handle for controlling this overlay\n\t\treturn {\n\t\t\thide: () => {\n\t\t\t\tconst index = this.overlayStack.indexOf(entry);\n\t\t\t\tif (index !== -1) {\n\t\t\t\t\tthis.clearOverlayFocusRestoreFor(entry);\n\t\t\t\t\tthis.retargetOverlayPreFocus(entry);\n\t\t\t\t\tthis.overlayStack.splice(index, 1);\n\t\t\t\t\t// Restore focus if this overlay had focus\n\t\t\t\t\tif (this.focusedComponent === component) {\n\t\t\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\t\t\tthis.setFocus(topVisible?.component ?? entry.preFocus);\n\t\t\t\t\t}\n\t\t\t\t\tif (this.overlayStack.length === 0 && !this.showHardwareCursor) {\n\t\t\t\t\t\tthis.terminal.hideCursor();\n\t\t\t\t\t}\n\t\t\t\t\tthis.requestRender();\n\t\t\t\t}\n\t\t\t},\n\t\t\tsetHidden: (hidden: boolean) => {\n\t\t\t\tif (entry.hidden === hidden) return;\n\t\t\t\tentry.hidden = hidden;\n\t\t\t\t// Update focus when hiding/showing\n\t\t\t\tif (hidden) {\n\t\t\t\t\tthis.clearOverlayFocusRestoreFor(entry);\n\t\t\t\t\t// If this overlay had focus, move focus to next visible or preFocus\n\t\t\t\t\tif (this.focusedComponent === component) {\n\t\t\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\t\t\tthis.setFocus(topVisible?.component ?? entry.preFocus);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Restore focus to this overlay when showing (if it's actually visible)\n\t\t\t\t\tif (!options?.nonCapturing && this.isOverlayVisible(entry)) {\n\t\t\t\t\t\tentry.focusOrder = ++this.focusOrderCounter;\n\t\t\t\t\t\tthis.setFocus(component);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tisHidden: () => entry.hidden,\n\t\t\tfocus: () => {\n\t\t\t\tif (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry)) return;\n\t\t\t\tentry.focusOrder = ++this.focusOrderCounter;\n\t\t\t\tthis.setFocus(component);\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tunfocus: (unfocusOptions) => {\n\t\t\t\tconst isFocused = this.focusedComponent === component;\n\t\t\t\tconst restoreState = this.overlayFocusRestore;\n\t\t\t\tconst hasPendingRestore = restoreState.status !== \"inactive\" && restoreState.overlay === entry;\n\t\t\t\tif (!isFocused && !hasPendingRestore) return;\n\t\t\t\tif (\n\t\t\t\t\trestoreState.status === \"blocked\" &&\n\t\t\t\t\trestoreState.overlay === entry &&\n\t\t\t\t\tthis.focusedComponent === restoreState.blockedBy\n\t\t\t\t) {\n\t\t\t\t\tif (unfocusOptions) {\n\t\t\t\t\t\tthis.overlayFocusRestore = {\n\t\t\t\t\t\t\tstatus: \"blocked\",\n\t\t\t\t\t\t\toverlay: entry,\n\t\t\t\t\t\t\tblockedBy: restoreState.blockedBy,\n\t\t\t\t\t\t\tresume: { status: \"focus-target\", target: unfocusOptions.target },\n\t\t\t\t\t\t};\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.clearOverlayFocusRestore();\n\t\t\t\t\t}\n\t\t\t\t\tthis.requestRender();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.clearOverlayFocusRestoreFor(entry);\n\t\t\t\tif (isFocused || unfocusOptions) {\n\t\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\t\tconst fallbackTarget = topVisible && topVisible !== entry ? topVisible.component : entry.preFocus;\n\t\t\t\t\tthis.setFocus(unfocusOptions ? unfocusOptions.target : fallbackTarget);\n\t\t\t\t}\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tisFocused: () => this.focusedComponent === component,\n\t\t};\n\t}\n\n\t/** Hide the topmost overlay and restore previous focus. */\n\thideOverlay(): void {\n\t\tconst overlay = this.overlayStack[this.overlayStack.length - 1];\n\t\tif (!overlay) return;\n\t\tthis.clearOverlayFocusRestoreFor(overlay);\n\t\tthis.retargetOverlayPreFocus(overlay);\n\t\tthis.overlayStack.pop();\n\t\tif (this.focusedComponent === overlay.component) {\n\t\t\t// Find topmost visible overlay, or fall back to preFocus\n\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\tthis.setFocus(topVisible?.component ?? overlay.preFocus);\n\t\t}\n\t\tif (this.overlayStack.length === 0) this.terminal.hideCursor();\n\t\tthis.requestRender();\n\t}\n\n\t/** Check if there are any visible overlays */\n\thasOverlay(): boolean {\n\t\treturn this.overlayStack.some((o) => this.isOverlayVisible(o));\n\t}\n\n\t/** Check if an overlay entry is currently visible */\n\tprivate isOverlayVisible(entry: OverlayStackEntry): boolean {\n\t\tif (entry.hidden) return false;\n\t\tif (entry.options?.visible) {\n\t\t\treturn entry.options.visible(this.terminal.columns, this.terminal.rows);\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Find the visual-frontmost visible capturing overlay, if any */\n\tprivate getTopmostVisibleOverlay(): OverlayStackEntry | undefined {\n\t\tlet topmost: OverlayStackEntry | undefined;\n\t\tfor (const overlay of this.overlayStack) {\n\t\t\tif (overlay.options?.nonCapturing || !this.isOverlayVisible(overlay)) continue;\n\t\t\tif (!topmost || overlay.focusOrder > topmost.focusOrder) {\n\t\t\t\ttopmost = overlay;\n\t\t\t}\n\t\t}\n\t\treturn topmost;\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tfor (const overlay of this.overlayStack) overlay.component.invalidate?.();\n\t}\n\n\tstart(): void {\n\t\tthis.stopped = false;\n\t\tthis.terminal.start(\n\t\t\t(data) => this.handleInput(data),\n\t\t\t() => this.requestRender(),\n\t\t);\n\t\tif (!this.showHardwareCursor) {\n\t\t\tthis.terminal.hideCursor();\n\t\t}\n\t\tthis.queryCellSize();\n\t\tthis.setupMouseListener();\n\t\tthis.requestRender();\n\t}\n\n\taddInputListener(listener: InputListener): () => void {\n\t\tthis.inputListeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.inputListeners.delete(listener);\n\t\t};\n\t}\n\n\tremoveInputListener(listener: InputListener): void {\n\t\tthis.inputListeners.delete(listener);\n\t}\n\n\tprivate queryCellSize(): void {\n\t\t// Only query if terminal supports images (cell size is only used for image rendering)\n\t\tif (!getCapabilities().images) {\n\t\t\treturn;\n\t\t}\n\t\t// Query terminal for cell size in pixels: CSI 16 t\n\t\t// Response format: CSI 6 ; height ; width t\n\t\tthis.terminal.write(\"\\x1b[16t\");\n\t}\n\n\tstop(): void {\n\t\tthis.stopped = true;\n\t\tif (this.renderTimer) {\n\t\t\tclearTimeout(this.renderTimer);\n\t\t\tthis.renderTimer = undefined;\n\t\t}\n\t\tif (this.scrollDebounceTimer) {\n\t\t\tclearTimeout(this.scrollDebounceTimer);\n\t\t\tthis.scrollDebounceTimer = null;\n\t\t}\n\t\tthis.clearAutoScrollTimer();\n\t\tthis.removeMouseListener();\n\t\t// Move cursor to the end of the content to prevent overwriting/artifacts on exit\n\t\tif (this.previousLines.length > 0) {\n\t\t\tconst targetRow = this.previousLines.length; // Line after the last content\n\t\t\tconst lineDiff = targetRow - this.hardwareCursorRow;\n\t\t\tif (lineDiff > 0) {\n\t\t\t\tthis.terminal.write(`\\x1b[${lineDiff}B`);\n\t\t\t} else if (lineDiff < 0) {\n\t\t\t\tthis.terminal.write(`\\x1b[${-lineDiff}A`);\n\t\t\t}\n\t\t\tthis.terminal.write(\"\\r\\n\");\n\t\t}\n\n\t\tthis.terminal.showCursor();\n\t\t// Reset cursor shape to user default on exit\n\t\tthis.terminal.write(\"\\x1b[0 q\");\n\t\tthis.terminal.stop();\n\t}\n\n\tprivate setupMouseListener(): void {\n\t\tconst stdinBuffer = this.terminal.stdinBuffer;\n\t\tif (!stdinBuffer) return;\n\t\tconst handler = (event: MouseEvent) => this.handleMouseEvent(event);\n\t\tstdinBuffer.on(\"mouse\", handler);\n\t\tthis.mouseListenerRemover = () => {\n\t\t\tstdinBuffer.removeListener(\"mouse\", handler);\n\t\t};\n\t}\n\n\tprivate removeMouseListener(): void {\n\t\tif (this.mouseListenerRemover) {\n\t\t\tthis.mouseListenerRemover();\n\t\t\tthis.mouseListenerRemover = undefined;\n\t\t}\n\t}\n\n\thandleMouseEvent(event: MouseEvent): void {\n\t\tif (event.type === \"mouseWheel\") {\n\t\t\tthis.lastMouseWheelTime = Date.now();\n\t\t\tif (this.focusedComponent?.handleInput) {\n\t\t\t\tconst direction = event.button === 64 ? \"scrollUp\" : \"scrollDown\";\n\t\t\t\tconst consumed = this.focusedComponent.handleInput(`\\x1b[${direction}`);\n\t\t\t\tthis.requestRender();\n\t\t\t\tif (consumed) return;\n\t\t\t}\n\t\t\t// Aggregate scroll delta for debouncing: first event flushes immediately,\n\t\t\t// subsequent events within the debounce window are accumulated and flushed once\n\t\t\tconst delta = event.button === 64 ? AUTO_SCROLL_ROWS : -AUTO_SCROLL_ROWS;\n\t\t\tthis.pendingScrollDelta += delta;\n\t\t\tif (!this.scrollDebounceTimer) {\n\t\t\t\t// First event: flush immediately for responsive feel\n\t\t\t\tthis.flushPendingScroll();\n\t\t\t\tthis.scrollDebounceTimer = setTimeout(() => {\n\t\t\t\t\tthis.scrollDebounceTimer = null;\n\t\t\t\t\tthis.flushPendingScroll();\n\t\t\t\t}, TUI.SCROLL_DEBOUNCE_MS);\n\t\t\t}\n\t\t\t// Otherwise: delta is accumulated, will be flushed when timer fires\n\t\t\treturn;\n\t\t}\n\t\tif (event.button !== 0) return;\n\t\tif (event.type === \"mouseDown\") {\n\t\t\tconst screenRow = event.row - 1;\n\t\t\tconst rawCol = event.col - 1;\n\t\t\tconst bufferRow = this.screenToBufferRow(screenRow);\n\t\t\tconst clip = this.getSelectionClipForRow(screenRow);\n\t\t\tconst line =\n\t\t\t\tclip != null && screenRow < this.currentCompositedLines.length\n\t\t\t\t\t? this.currentCompositedLines[screenRow]\n\t\t\t\t\t: this.currentFullLines[bufferRow];\n\t\t\tconst col = line != null ? snapColToGraphemeBoundary(line, rawCol) : rawCol;\n\t\t\tthis.selection = {\n\t\t\t\tactive: true,\n\t\t\t\tanchorRow: bufferRow,\n\t\t\t\tanchorCol: col,\n\t\t\t\tfocusRow: bufferRow,\n\t\t\t\tfocusCol: col,\n\t\t\t};\n\t\t\tthis.requestRender();\n\t\t} else if (event.type === \"mouseMove\" && this.selection) {\n\t\t\tconst screenRow = event.row - 1;\n\t\t\tconst rawCol = event.col - 1;\n\t\t\tconst bufferRow = this.screenToBufferRow(screenRow);\n\t\t\tconst clip = this.getSelectionClipForRow(screenRow);\n\t\t\tconst line =\n\t\t\t\tclip != null && screenRow < this.currentCompositedLines.length\n\t\t\t\t\t? this.currentCompositedLines[screenRow]\n\t\t\t\t\t: this.currentFullLines[bufferRow];\n\t\t\tconst col = line != null ? snapColToGraphemeBoundary(line, rawCol) : rawCol;\n\t\t\tthis.selection.focusRow = bufferRow;\n\t\t\tthis.selection.focusCol = col;\n\t\t\tif (event.row <= 1) {\n\t\t\t\tthis.startAutoScroll(-1);\n\t\t\t} else if (event.row >= this.lastScrollableViewport) {\n\t\t\t\t// Trigger downward autoScroll at the bottom of the scrollable area,\n\t\t\t\t// not the terminal bottom — the latter would require crossing any fixed\n\t\t\t\t// bottom region (e.g. the input box) before scrolling kicks in.\n\t\t\t\tthis.startAutoScroll(1);\n\t\t\t} else {\n\t\t\t\tthis.clearAutoScrollTimer();\n\t\t\t}\n\t\t\tthis.requestRender();\n\t\t} else if (event.type === \"mouseUp\" && this.selection) {\n\t\t\tconst sel = this.selection;\n\t\t\t// Skip copy on plain click (no drag) to avoid polluting clipboard\n\t\t\tconst hasDragged = sel.anchorRow !== sel.focusRow || sel.anchorCol !== sel.focusCol;\n\t\t\tconst text = hasDragged ? this.extractSelectionText() : \"\";\n\t\t\tthis.clearAutoScrollTimer();\n\t\t\tthis.selection = null;\n\t\t\tthis.requestRender();\n\t\t\tif (text.trim() && this.onCopySelection) {\n\t\t\t\tthis.onCopySelection(text);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getMaxScrollOffset(): number {\n\t\tconst width = this.terminal.columns;\n\t\tconst height = this.terminal.rows;\n\t\tconst childLines: string[][] = [];\n\t\tfor (const child of this.children) {\n\t\t\tchildLines.push(child.render(width));\n\t\t}\n\t\tconst fixedCount = this.fixedBottomCount;\n\t\tlet scrollableLines = 0;\n\t\tlet fixedLines = 0;\n\t\tfor (let i = 0; i < childLines.length; i++) {\n\t\t\tif (i >= childLines.length - fixedCount) {\n\t\t\t\tfixedLines += childLines[i].length;\n\t\t\t} else {\n\t\t\t\tscrollableLines += childLines[i].length;\n\t\t\t}\n\t\t}\n\t\tconst scrollableViewport = Math.max(0, height - fixedLines);\n\t\treturn Math.max(0, scrollableLines - scrollableViewport);\n\t}\n\n\t/** Flush pending scroll delta and trigger a single render */\n\tprivate flushPendingScroll(): void {\n\t\tif (this.pendingScrollDelta === 0) return;\n\t\tconst delta = this.pendingScrollDelta;\n\t\tthis.pendingScrollDelta = 0;\n\t\tif (delta > 0) {\n\t\t\tthis.autoFollow = false;\n\t\t\tthis.scrollOffset = Math.min(this.getMaxScrollOffset(), this.scrollOffset + delta);\n\t\t} else {\n\t\t\tthis.scrollOffset = Math.max(0, this.scrollOffset + delta);\n\t\t\tif (this.scrollOffset === 0) this.autoFollow = true;\n\t\t}\n\t\tthis.onScrollOffsetChange?.(this.scrollOffset);\n\t\tthis.requestRender();\n\t}\n\n\tgetScrollOffset(): number {\n\t\treturn this.scrollOffset;\n\t}\n\n\tsetScrollOffset(offset: number): void {\n\t\tthis.scrollOffset = offset;\n\t\tthis.autoFollow = offset === 0;\n\t\tthis.onScrollOffsetChange?.(offset);\n\t\tthis.requestRender();\n\t}\n\n\tresetScrollOffset(): void {\n\t\tthis.scrollOffset = 0;\n\t\tthis.autoFollow = true;\n\t\tthis.onScrollOffsetChange?.(0);\n\t\tthis.requestRender();\n\t}\n\n\tgetAutoFollow(): boolean {\n\t\treturn this.autoFollow;\n\t}\n\n\tsetAutoFollow(value: boolean): void {\n\t\tif (this.autoFollow === value) return;\n\t\tthis.autoFollow = value;\n\t\tif (value) {\n\t\t\tthis.scrollOffset = 0;\n\t\t\tthis.onScrollOffsetChange?.(0);\n\t\t\tthis.requestRender();\n\t\t}\n\t}\n\n\tsetFixedBottomCount(count: number): void {\n\t\tthis.fixedBottomCount = count;\n\t}\n\n\tprivate startAutoScroll(direction: -1 | 1): void {\n\t\t// 同方向已运行则不重启,避免定时器堆积\n\t\tif (this.autoScrollTimer && this.autoScrollDirection === direction) return;\n\t\tthis.clearAutoScrollTimer();\n\t\tthis.autoFollow = false;\n\t\tthis.autoScrollDirection = direction;\n\t\tthis.autoScrollTimer = setInterval(() => {\n\t\t\tconst maxOffset = this.getMaxScrollOffset();\n\t\t\tif (direction < 0) {\n\t\t\t\t// 向旧内容方向滚动(视口顶向缓冲区起始扩展)\n\t\t\t\tif (this.scrollOffset >= maxOffset) return;\n\t\t\t\tthis.scrollOffset = Math.min(maxOffset, this.scrollOffset + AUTO_SCROLL_ROWS);\n\t\t\t\tif (this.selection) {\n\t\t\t\t\t// focus 指向视口顶行(刚滚入视野的更旧内容)\n\t\t\t\t\tthis.selection.focusRow = this.currentScrollableViewportTop;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// 向新内容方向滚动(视口顶向缓冲区末尾收缩)\n\t\t\t\tif (this.scrollOffset <= 0) return;\n\t\t\t\tthis.scrollOffset = Math.max(0, this.scrollOffset - AUTO_SCROLL_ROWS);\n\t\t\t\tif (this.selection) {\n\t\t\t\t\t// focus 指向视口底行(刚滚入视野的更新内容)\n\t\t\t\t\tthis.selection.focusRow = this.currentScrollableViewportTop + this.lastScrollableViewport - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.onScrollOffsetChange?.(this.scrollOffset);\n\t\t\tthis.requestRender();\n\t\t}, AUTO_SCROLL_INTERVAL_MS);\n\t}\n\n\tprivate clearAutoScrollTimer(): void {\n\t\tif (this.autoScrollTimer) {\n\t\t\tclearInterval(this.autoScrollTimer);\n\t\t\tthis.autoScrollTimer = null;\n\t\t}\n\t}\n\n\t/**\n\t * Clear the current selection and stop any active autoScroll.\n\t * Called by overlays when their internal scroll changes, to prevent\n\t * stale selection highlighting on shifted content.\n\t */\n\tclearSelection(): void {\n\t\tthis.clearAutoScrollTimer();\n\t\tthis.selection = null;\n\t\tthis.requestRender();\n\t}\n\n\tprivate extractSelectionText(): string {\n\t\tif (!this.selection) return \"\";\n\t\tconst sel = this.selection;\n\t\tconst lines = this.currentFullLines;\n\t\tif (lines.length === 0) return \"\";\n\t\tconst startRow = Math.min(sel.anchorRow, sel.focusRow);\n\t\tconst endRow = Math.max(sel.anchorRow, sel.focusRow);\n\t\tlet startCol: number;\n\t\tlet endCol: number;\n\t\tif (startRow === endRow) {\n\t\t\tstartCol = Math.min(sel.anchorCol, sel.focusCol);\n\t\t\tendCol = Math.max(sel.anchorCol, sel.focusCol);\n\t\t} else {\n\t\t\tstartCol = startRow === sel.anchorRow ? sel.anchorCol : sel.focusCol;\n\t\t\tendCol = endRow === sel.anchorRow ? sel.anchorCol : sel.focusCol;\n\t\t}\n\t\tconst parts: string[] = [];\n\t\tfor (let row = startRow; row <= endRow; row++) {\n\t\t\tif (row < 0 || row >= lines.length) continue;\n\t\t\t// Apply selectionClip from overlays that cover this screen row\n\t\t\tconst screenRow = this.bufferToScreenRow(row);\n\t\t\tconst clip = screenRow >= 0 ? this.getSelectionClipForRow(screenRow) : null;\n\t\t\t// Overlay-covered rows: extract from composited lines (overlay content).\n\t\t\t// Non-overlay rows: extract from full buffer (supports cross-viewport selection).\n\t\t\tconst line =\n\t\t\t\tclip != null && screenRow >= 0 && screenRow < this.currentCompositedLines.length\n\t\t\t\t\t? this.currentCompositedLines[screenRow]\n\t\t\t\t\t: lines[row];\n\t\t\tconst rowStartCol = row === startRow ? startCol : 0;\n\t\t\tconst rowEndCol = row === endRow ? endCol : visibleWidth(line) - 1;\n\t\t\tlet clipStart = rowStartCol;\n\t\t\tlet clipEnd = rowEndCol;\n\t\t\tif (clip) {\n\t\t\t\t// Clip the selection range to the selectable region within the overlay\n\t\t\t\tclipStart = Math.max(clipStart, clip.col);\n\t\t\t\tclipEnd = Math.min(clipEnd, clip.col + clip.width - 1);\n\t\t\t}\n\t\t\tif (clipStart > clipEnd) continue;\n\t\t\tconst extracted = stripAnsi(sliceByColumn(line, clipStart, clipEnd - clipStart + 1));\n\t\t\t// Trim trailing whitespace from composited lines since compositeLineAt\n\t\t\t// pads them to terminal width with spaces, followed by ANSI resets.\n\t\t\tparts.push(clip ? extracted.trimEnd() : extracted);\n\t\t}\n\t\treturn parts.join(\"\\n\");\n\t}\n\n\t/**\n\t * Get the selection clip region for a given screen row.\n\t * If any overlay with a selectionClip callback covers this row,\n\t * returns the clip region to restrict selection to that area.\n\t */\n\tprivate getSelectionClipForRow(screenRow: number): { col: number; width: number } | null {\n\t\tfor (const layout of this.renderedOverlayLayouts) {\n\t\t\t// Check if this screen row falls within the overlay's row range\n\t\t\tif (screenRow >= layout.row && screenRow < layout.row + layout.height) {\n\t\t\t\tif (layout.selectionClip) {\n\t\t\t\t\tconst clip = layout.selectionClip(screenRow);\n\t\t\t\t\tif (clip) {\n\t\t\t\t\t\t// Adjust clip col to be relative to the overlay's position\n\t\t\t\t\t\treturn { col: layout.col + clip.col, width: clip.width };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Convert a screen row (0-indexed terminal row) to a buffer-absolute row index\n\t * in `this.currentFullLines`. Used by mouseDown/mouseMove to set selection\n\t * anchor/focus in stable buffer coordinates that survive scrolling.\n\t *\n\t * - Screen rows in the scrollable area map to:\n\t * currentScrollableViewportTop + screenRow\n\t * - Screen rows in the fixed area map to:\n\t * currentScrollableLinesLength + (screenRow - lastScrollableViewport)\n\t */\n\tprivate screenToBufferRow(screenRow: number): number {\n\t\tconst svp = this.lastScrollableViewport;\n\t\tif (screenRow < svp) {\n\t\t\treturn this.currentScrollableViewportTop + screenRow;\n\t\t}\n\t\treturn this.currentScrollableLinesLength + (screenRow - svp);\n\t}\n\n\t/**\n\t * Convert a buffer-absolute row index back to a screen row.\n\t * Returns -1 if the buffer row is a scrollable line currently outside the viewport.\n\t * Fixed-area buffer rows always map to a visible screen row.\n\t */\n\tprivate bufferToScreenRow(bufferRow: number): number {\n\t\tconst scrollableLen = this.currentScrollableLinesLength;\n\t\tif (bufferRow < scrollableLen) {\n\t\t\tconst screenRow = bufferRow - this.currentScrollableViewportTop;\n\t\t\tif (screenRow < 0 || screenRow >= this.lastScrollableViewport) return -1;\n\t\t\treturn screenRow;\n\t\t}\n\t\treturn this.lastScrollableViewport + (bufferRow - scrollableLen);\n\t}\n\n\tprivate applySelectionHighlight(newLines: string[], height: number): void {\n\t\tif (!this.selection) return;\n\t\tconst sel = this.selection;\n\t\tconst startBufferRow = Math.min(sel.anchorRow, sel.focusRow);\n\t\tconst endBufferRow = Math.max(sel.anchorRow, sel.focusRow);\n\t\tlet startCol: number;\n\t\tlet endCol: number;\n\t\tif (startBufferRow === endBufferRow) {\n\t\t\tstartCol = Math.min(sel.anchorCol, sel.focusCol);\n\t\t\tendCol = Math.max(sel.anchorCol, sel.focusCol);\n\t\t} else {\n\t\t\tstartCol = startBufferRow === sel.anchorRow ? sel.anchorCol : sel.focusCol;\n\t\t\tendCol = endBufferRow === sel.anchorRow ? sel.anchorCol : sel.focusCol;\n\t\t}\n\n\t\tfor (let bufferRow = startBufferRow; bufferRow <= endBufferRow; bufferRow++) {\n\t\t\tconst screenRow = this.bufferToScreenRow(bufferRow);\n\t\t\tif (screenRow < 0 || screenRow >= height) continue;\n\t\t\tif (bufferRow < 0 || bufferRow >= this.currentFullLines.length) continue;\n\t\t\tconst targetLine = newLines[screenRow];\n\t\t\tif (!targetLine || isImageLine(targetLine)) continue;\n\t\t\tconst lineVisibleWidth = visibleWidth(targetLine);\n\t\t\tlet colStart = bufferRow === startBufferRow ? Math.min(startCol, lineVisibleWidth) : 0;\n\t\t\tlet colEnd = bufferRow === endBufferRow ? Math.min(endCol, lineVisibleWidth - 1) : lineVisibleWidth - 1;\n\t\t\t// Apply selectionClip from overlays that cover this screen row\n\t\t\tconst clip = this.getSelectionClipForRow(screenRow);\n\t\t\tif (clip) {\n\t\t\t\tcolStart = Math.max(colStart, clip.col);\n\t\t\t\tcolEnd = Math.min(colEnd, clip.col + clip.width - 1);\n\t\t\t}\n\t\t\tif (colStart > colEnd) continue;\n\t\t\tconst before = sliceByColumn(targetLine, 0, colStart, true);\n\t\t\tconst highlighted = sliceByColumn(targetLine, colStart, colEnd - colStart + 1);\n\t\t\tconst after =\n\t\t\t\tcolEnd + 1 < lineVisibleWidth ? sliceByColumn(targetLine, colEnd + 1, lineVisibleWidth - colEnd - 1) : \"\";\n\t\t\t// Preserve reverse video across SGR resets inside the highlighted region.\n\t\t\t// \\x1b[0m resets ALL attributes including \\x1b[7m (reverse video),\n\t\t\t// which would break the selection highlight. Re-apply \\x1b[7m after each reset.\n\t\t\tconst preservedHighlight = highlighted.replace(/\\x1b\\[0m/g, \"\\x1b[0m\\x1b[7m\");\n\t\t\tnewLines[screenRow] = `${before}\\x1b[7m${preservedHighlight}\\x1b[27m${after}`;\n\t\t}\n\t}\n\n\trequestRender(force = false): void {\n\t\tif (force) {\n\t\t\tthis.previousLines = [];\n\t\t\tthis.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear\n\t\t\tthis.previousHeight = -1; // -1 triggers heightChanged, forcing a full clear\n\t\t\tthis.cursorRow = 0;\n\t\t\tthis.hardwareCursorRow = 0;\n\t\t\tthis.maxLinesRendered = 0;\n\t\t\tthis.previousViewportTop = 0;\n\t\t\tif (this.renderTimer) {\n\t\t\t\tclearTimeout(this.renderTimer);\n\t\t\t\tthis.renderTimer = undefined;\n\t\t\t}\n\t\t\tthis.renderRequested = true;\n\t\t\tprocess.nextTick(() => {\n\t\t\t\tif (this.stopped || !this.renderRequested) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.renderRequested = false;\n\t\t\t\tthis.lastRenderAt = performance.now();\n\t\t\t\tthis.doRender();\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (this.renderRequested) return;\n\t\tthis.renderRequested = true;\n\t\tprocess.nextTick(() => this.scheduleRender());\n\t}\n\n\tprivate scheduleRender(): void {\n\t\tif (this.stopped || this.renderTimer || !this.renderRequested) {\n\t\t\treturn;\n\t\t}\n\t\tconst elapsed = performance.now() - this.lastRenderAt;\n\t\tconst delay = Math.max(0, TUI.MIN_RENDER_INTERVAL_MS - elapsed);\n\t\tthis.renderTimer = setTimeout(() => {\n\t\t\tthis.renderTimer = undefined;\n\t\t\tif (this.stopped || !this.renderRequested) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renderRequested = false;\n\t\t\tthis.lastRenderAt = performance.now();\n\t\t\tthis.doRender();\n\t\t\tif (this.renderRequested) {\n\t\t\t\tthis.scheduleRender();\n\t\t\t}\n\t\t}, delay);\n\t}\n\n\tprivate handleInput(data: string): void {\n\t\tif (this.inputListeners.size > 0) {\n\t\t\tlet current = data;\n\t\t\tfor (const listener of this.inputListeners) {\n\t\t\t\tconst result = listener(current);\n\t\t\t\tif (result?.consume) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (result?.data !== undefined) {\n\t\t\t\t\tcurrent = result.data;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (current.length === 0) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdata = current;\n\t\t}\n\n\t\t// Consume terminal cell size responses without blocking unrelated input.\n\t\tif (this.consumeCellSizeResponse(data)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Global debug key handler (Shift+Ctrl+D)\n\t\tif (matchesKey(data, \"shift+ctrl+d\") && this.onDebug) {\n\t\t\tthis.onDebug();\n\t\t\treturn;\n\t\t}\n\n\t\t// If focused component is an overlay, verify it's still visible\n\t\t// (visibility can change due to terminal resize or visible() callback)\n\t\tconst focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);\n\t\tif (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {\n\t\t\t// Focused overlay is no longer visible, redirect to topmost visible overlay\n\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\tif (topVisible) {\n\t\t\t\tthis.setFocus(topVisible.component);\n\t\t\t} else {\n\t\t\t\tthis.setFocusInternal({ component: focusedOverlay.preFocus, overlayFocusRestore: \"preserve\" });\n\t\t\t}\n\t\t}\n\n\t\tconst focusIsOverlay = this.overlayStack.some((o) => o.component === this.focusedComponent);\n\t\tif (!focusIsOverlay) {\n\t\t\tconst restoreState = this.getVisibleOverlayFocusRestore();\n\t\t\tif (restoreState.status === \"eligible\") {\n\t\t\t\tthis.setFocus(restoreState.overlay.component);\n\t\t\t} else if (restoreState.status === \"blocked\" && restoreState.blockedBy !== this.focusedComponent) {\n\t\t\t\tif (restoreState.resume.status === \"restore-overlay\") {\n\t\t\t\t\tthis.setFocus(restoreState.overlay.component);\n\t\t\t\t} else {\n\t\t\t\t\tthis.clearOverlayFocusRestore();\n\t\t\t\t\tthis.setFocus(restoreState.resume.target);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Suppress arrow keys that arrive shortly after a mouse wheel event.\n\t\t// Some terminals (or intermediate layers like tmux) occasionally convert\n\t\t// scroll events into arrow-key sequences; without this guard those\n\t\t// spurious keys trigger unwanted actions such as input-history navigation.\n\t\tif (\n\t\t\tDate.now() - this.lastMouseWheelTime < TUI.MOUSE_WHEEL_SUPPRESS_MS &&\n\t\t\t(matchesKey(data, \"up\") || matchesKey(data, \"down\"))\n\t\t) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Pass input to focused component first. If it returns true, it consumed the input.\n\t\tif (this.focusedComponent?.handleInput) {\n\t\t\t// Filter out key release events unless component opts in\n\t\t\tif (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst consumed = this.focusedComponent.handleInput(data);\n\t\t\tthis.requestRender();\n\t\t\tif (consumed) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Fallback: TUI handles scroll keys when focused component didn't consume them\n\t\tif (matchesKey(data, \"pageUp\")) {\n\t\t\tconst pageSize = this.lastScrollableViewport || this.terminal.rows - 2;\n\t\t\tthis.setScrollOffset(this.scrollOffset + pageSize);\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, \"pageDown\")) {\n\t\t\tconst pageSize = this.lastScrollableViewport || this.terminal.rows - 2;\n\t\t\tthis.setScrollOffset(Math.max(0, this.scrollOffset - pageSize));\n\t\t\treturn;\n\t\t}\n\t\t// Ctrl+Home / Ctrl+End: scroll to top/bottom of content\n\t\tif (matchesKey(data, \"ctrl+home\")) {\n\t\t\tthis.setScrollOffset(this.getMaxScrollOffset());\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, \"ctrl+end\")) {\n\t\t\tthis.setScrollOffset(0);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate consumeCellSizeResponse(data: string): boolean {\n\t\t// Response format: ESC [ 6 ; height ; width t\n\t\tconst match = data.match(/^\\x1b\\[6;(\\d+);(\\d+)t$/);\n\t\tif (!match) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst heightPx = parseInt(match[1], 10);\n\t\tconst widthPx = parseInt(match[2], 10);\n\t\tif (heightPx <= 0 || widthPx <= 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\tsetCellDimensions({ widthPx, heightPx });\n\t\t// Invalidate all components so images re-render with correct dimensions.\n\t\tthis.invalidate();\n\t\tthis.requestRender();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Resolve overlay layout from options.\n\t * Returns { width, row, col, maxHeight } for rendering.\n\t */\n\tprivate resolveOverlayLayout(\n\t\toptions: OverlayOptions | undefined,\n\t\toverlayHeight: number,\n\t\ttermWidth: number,\n\t\ttermHeight: number,\n\t): { width: number; row: number; col: number; maxHeight: number | undefined } {\n\t\tconst opt = options ?? {};\n\n\t\t// Parse margin (clamp to non-negative)\n\t\tconst margin =\n\t\t\ttypeof opt.margin === \"number\"\n\t\t\t\t? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }\n\t\t\t\t: (opt.margin ?? {});\n\t\tconst marginTop = Math.max(0, margin.top ?? 0);\n\t\tconst marginRight = Math.max(0, margin.right ?? 0);\n\t\tconst marginBottom = Math.max(0, margin.bottom ?? 0);\n\t\tconst marginLeft = Math.max(0, margin.left ?? 0);\n\n\t\t// Available space after margins\n\t\tconst availWidth = Math.max(1, termWidth - marginLeft - marginRight);\n\t\tconst availHeight = Math.max(1, termHeight - marginTop - marginBottom);\n\n\t\t// === Resolve width ===\n\t\tlet width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);\n\t\t// Apply minWidth\n\t\tif (opt.minWidth !== undefined) {\n\t\t\twidth = Math.max(width, opt.minWidth);\n\t\t}\n\t\t// Clamp to available space\n\t\twidth = Math.max(1, Math.min(width, availWidth));\n\n\t\t// === Resolve maxHeight ===\n\t\tlet maxHeight = parseSizeValue(opt.maxHeight, termHeight);\n\t\t// Clamp to available space\n\t\tif (maxHeight !== undefined) {\n\t\t\tmaxHeight = Math.max(1, Math.min(maxHeight, availHeight));\n\t\t}\n\n\t\t// Effective overlay height (may be clamped by maxHeight)\n\t\tconst effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;\n\n\t\t// === Resolve position ===\n\t\tlet row: number;\n\t\tlet col: number;\n\n\t\tif (opt.row !== undefined) {\n\t\t\tif (typeof opt.row === \"string\") {\n\t\t\t\t// Percentage: 0% = top, 100% = bottom (overlay stays within bounds)\n\t\t\t\tconst match = opt.row.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\t\t\t\tif (match) {\n\t\t\t\t\tconst maxRow = Math.max(0, availHeight - effectiveHeight);\n\t\t\t\t\tconst percent = parseFloat(match[1]) / 100;\n\t\t\t\t\trow = marginTop + Math.floor(maxRow * percent);\n\t\t\t\t} else {\n\t\t\t\t\t// Invalid format, fall back to center\n\t\t\t\t\trow = this.resolveAnchorRow(\"center\", effectiveHeight, availHeight, marginTop);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Absolute row position\n\t\t\t\trow = opt.row;\n\t\t\t}\n\t\t} else {\n\t\t\t// Anchor-based (default: center)\n\t\t\tconst anchor = opt.anchor ?? \"center\";\n\t\t\trow = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);\n\t\t}\n\n\t\tif (opt.col !== undefined) {\n\t\t\tif (typeof opt.col === \"string\") {\n\t\t\t\t// Percentage: 0% = left, 100% = right (overlay stays within bounds)\n\t\t\t\tconst match = opt.col.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\t\t\t\tif (match) {\n\t\t\t\t\tconst maxCol = Math.max(0, availWidth - width);\n\t\t\t\t\tconst percent = parseFloat(match[1]) / 100;\n\t\t\t\t\tcol = marginLeft + Math.floor(maxCol * percent);\n\t\t\t\t} else {\n\t\t\t\t\t// Invalid format, fall back to center\n\t\t\t\t\tcol = this.resolveAnchorCol(\"center\", width, availWidth, marginLeft);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Absolute column position\n\t\t\t\tcol = opt.col;\n\t\t\t}\n\t\t} else {\n\t\t\t// Anchor-based (default: center)\n\t\t\tconst anchor = opt.anchor ?? \"center\";\n\t\t\tcol = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);\n\t\t}\n\n\t\t// Apply offsets\n\t\tif (opt.offsetY !== undefined) row += opt.offsetY;\n\t\tif (opt.offsetX !== undefined) col += opt.offsetX;\n\n\t\t// Clamp to terminal bounds (respecting margins)\n\t\trow = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));\n\t\tcol = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));\n\n\t\treturn { width, row, col, maxHeight };\n\t}\n\n\tprivate resolveAnchorRow(anchor: OverlayAnchor, height: number, availHeight: number, marginTop: number): number {\n\t\tswitch (anchor) {\n\t\t\tcase \"top-left\":\n\t\t\tcase \"top-center\":\n\t\t\tcase \"top-right\":\n\t\t\t\treturn marginTop;\n\t\t\tcase \"bottom-left\":\n\t\t\tcase \"bottom-center\":\n\t\t\tcase \"bottom-right\":\n\t\t\t\treturn marginTop + availHeight - height;\n\t\t\tcase \"left-center\":\n\t\t\tcase \"center\":\n\t\t\tcase \"right-center\":\n\t\t\t\treturn marginTop + Math.floor((availHeight - height) / 2);\n\t\t}\n\t}\n\n\tprivate resolveAnchorCol(anchor: OverlayAnchor, width: number, availWidth: number, marginLeft: number): number {\n\t\tswitch (anchor) {\n\t\t\tcase \"top-left\":\n\t\t\tcase \"left-center\":\n\t\t\tcase \"bottom-left\":\n\t\t\t\treturn marginLeft;\n\t\t\tcase \"top-right\":\n\t\t\tcase \"right-center\":\n\t\t\tcase \"bottom-right\":\n\t\t\t\treturn marginLeft + availWidth - width;\n\t\t\tcase \"top-center\":\n\t\t\tcase \"center\":\n\t\t\tcase \"bottom-center\":\n\t\t\t\treturn marginLeft + Math.floor((availWidth - width) / 2);\n\t\t}\n\t}\n\n\t/** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */\n\tprivate compositeOverlays(lines: string[], termWidth: number, termHeight: number): string[] {\n\t\tconst result = [...lines];\n\n\t\t// Pre-render all visible overlays and calculate positions\n\t\tconst rendered: {\n\t\t\toverlayLines: string[];\n\t\t\trow: number;\n\t\t\tcol: number;\n\t\t\tw: number;\n\t\t\tbackground?: string;\n\t\t\tselectionClip?: (screenRow: number) => { col: number; width: number } | null;\n\t\t}[] = [];\n\t\tlet minLinesNeeded = result.length;\n\n\t\tconst visibleEntries = this.overlayStack.filter((e) => this.isOverlayVisible(e));\n\t\tvisibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);\n\t\tfor (const entry of visibleEntries) {\n\t\t\tconst { component, options } = entry;\n\n\t\t\t// Get layout with height=0 first to determine width and maxHeight\n\t\t\t// (width and maxHeight don't depend on overlay height)\n\t\t\tconst { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);\n\n\t\t\t// Render component at calculated width\n\t\t\tlet overlayLines = component.render(width);\n\n\t\t\t// Apply maxHeight if specified\n\t\t\tif (maxHeight !== undefined && overlayLines.length > maxHeight) {\n\t\t\t\toverlayLines = overlayLines.slice(0, maxHeight);\n\t\t\t}\n\n\t\t\t// Get final row/col with actual overlay height\n\t\t\tconst { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);\n\n\t\t\trendered.push({\n\t\t\t\toverlayLines,\n\t\t\t\trow,\n\t\t\t\tcol,\n\t\t\t\tw: width,\n\t\t\t\tbackground: options?.background,\n\t\t\t\tselectionClip: options?.selectionClip,\n\t\t\t});\n\t\t\tminLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);\n\t\t}\n\n\t\t// Cache overlay layouts for selection clip calculations\n\t\tthis.renderedOverlayLayouts = rendered.map(({ row, col, w, overlayLines, selectionClip }) => ({\n\t\t\trow,\n\t\t\tcol,\n\t\t\twidth: w,\n\t\t\theight: overlayLines.length,\n\t\t\tselectionClip,\n\t\t}));\n\n\t\t// Pad to at least terminal height so overlays have screen-relative positions.\n\t\t// Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing\n\t\t// inflation that pushed content into scrollback on terminal widen.\n\t\tconst workingHeight = Math.max(result.length, termHeight, minLinesNeeded);\n\n\t\t// Extend result with empty lines if content is too short for overlay placement or working area\n\t\twhile (result.length < workingHeight) {\n\t\t\tresult.push(\"\");\n\t\t}\n\n\t\tconst viewportStart = Math.max(0, workingHeight - termHeight);\n\n\t\t// Composite each overlay\n\t\tfor (const { overlayLines, row, col, w, background: bg } of rendered) {\n\t\t\tfor (let i = 0; i < overlayLines.length; i++) {\n\t\t\t\tconst idx = viewportStart + row + i;\n\t\t\t\tif (idx >= 0 && idx < result.length) {\n\t\t\t\t\t// Defensive: truncate overlay line to declared width before compositing\n\t\t\t\t\t// (components should already respect width, but this ensures it)\n\t\t\t\t\tconst truncatedOverlayLine =\n\t\t\t\t\t\tvisibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];\n\t\t\t\t\tlet baseLine = result[idx];\n\t\t\t\t\tif (bg) {\n\t\t\t\t\t\tbaseLine = this.applyOverlayBackground(baseLine, col, w, bg, termWidth);\n\t\t\t\t\t}\n\t\t\t\t\tresult[idx] = this.compositeLineAt(baseLine, truncatedOverlayLine, col, w, termWidth);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate static readonly SEGMENT_RESET = \"\\x1b[0m\\x1b]8;;\\x07\";\n\n\tprivate applyLineResets(lines: string[]): string[] {\n\t\tconst reset = TUI.SEGMENT_RESET;\n\t\tfor (let i = 0; i < lines.length; i++) {\n\t\t\tconst line = lines[i];\n\t\t\tif (!isImageLine(line)) {\n\t\t\t\tlines[i] = normalizeTerminalOutput(line) + reset;\n\t\t\t}\n\t\t}\n\t\treturn lines;\n\t}\n\n\tprivate collectKittyImageIds(lines: string[]): Set<number> {\n\t\tconst ids = new Set<number>();\n\t\tfor (const line of lines) {\n\t\t\tfor (const id of extractKittyImageIds(line)) {\n\t\t\t\tids.add(id);\n\t\t\t}\n\t\t}\n\t\treturn ids;\n\t}\n\n\tprivate deleteKittyImages(ids: Iterable<number>): string {\n\t\tlet buffer = \"\";\n\t\tfor (const id of ids) {\n\t\t\tbuffer += deleteKittyImage(id);\n\t\t}\n\t\treturn buffer;\n\t}\n\n\tprivate expandLastChangedForKittyImages(firstChanged: number, lastChanged: number): number {\n\t\tlet expandedLastChanged = lastChanged;\n\t\tfor (let i = firstChanged; i < this.previousLines.length; i++) {\n\t\t\tif (extractKittyImageIds(this.previousLines[i]).length > 0) {\n\t\t\t\texpandedLastChanged = Math.max(expandedLastChanged, i);\n\t\t\t}\n\t\t}\n\t\treturn expandedLastChanged;\n\t}\n\n\tprivate deleteChangedKittyImages(firstChanged: number, lastChanged: number): string {\n\t\tif (firstChanged < 0 || lastChanged < firstChanged) return \"\";\n\n\t\tconst ids = new Set<number>();\n\t\tconst maxLine = Math.min(lastChanged, this.previousLines.length - 1);\n\t\tfor (let i = firstChanged; i <= maxLine; i++) {\n\t\t\tfor (const id of extractKittyImageIds(this.previousLines[i] ?? \"\")) {\n\t\t\t\tids.add(id);\n\t\t\t}\n\t\t}\n\n\t\treturn this.deleteKittyImages(ids);\n\t}\n\n\t/** Apply background fill to the overlay region of a base line. */\n\tprivate applyOverlayBackground(\n\t\tbaseLine: string,\n\t\tstartCol: number,\n\t\toverlayWidth: number,\n\t\tbg: string,\n\t\ttotalWidth: number,\n\t): string {\n\t\tif (isImageLine(baseLine)) return baseLine;\n\t\tconst afterStart = startCol + overlayWidth;\n\t\tconst segments = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);\n\t\tconst r = TUI.SEGMENT_RESET;\n\t\tconst beforePad = Math.max(0, startCol - segments.beforeWidth);\n\t\tconst overlayFill = bg + \" \".repeat(overlayWidth) + r;\n\t\tconst afterTarget = Math.max(0, totalWidth - Math.max(startCol, segments.beforeWidth) - overlayWidth);\n\t\tconst afterPad = Math.max(0, afterTarget - segments.afterWidth);\n\t\treturn segments.before + \" \".repeat(beforePad) + r + overlayFill + segments.after + \" \".repeat(afterPad);\n\t}\n\n\t/** Splice overlay content into a base line at a specific column. Single-pass optimized. */\n\tprivate compositeLineAt(\n\t\tbaseLine: string,\n\t\toverlayLine: string,\n\t\tstartCol: number,\n\t\toverlayWidth: number,\n\t\ttotalWidth: number,\n\t): string {\n\t\tif (isImageLine(baseLine)) return baseLine;\n\n\t\t// Single pass through baseLine extracts both before and after segments\n\t\tconst afterStart = startCol + overlayWidth;\n\t\tconst base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);\n\n\t\t// Extract overlay with width tracking (strict=true to exclude wide chars at boundary)\n\t\tconst overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);\n\n\t\t// Pad segments to target widths\n\t\tconst beforePad = Math.max(0, startCol - base.beforeWidth);\n\t\tconst overlayPad = Math.max(0, overlayWidth - overlay.width);\n\t\tconst actualBeforeWidth = Math.max(startCol, base.beforeWidth);\n\t\tconst actualOverlayWidth = Math.max(overlayWidth, overlay.width);\n\t\tconst afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);\n\t\tconst afterPad = Math.max(0, afterTarget - base.afterWidth);\n\n\t\t// Compose result\n\t\tconst r = TUI.SEGMENT_RESET;\n\t\tconst result =\n\t\t\tbase.before +\n\t\t\t\" \".repeat(beforePad) +\n\t\t\tr +\n\t\t\toverlay.text +\n\t\t\t\" \".repeat(overlayPad) +\n\t\t\tr +\n\t\t\tbase.after +\n\t\t\t\" \".repeat(afterPad);\n\n\t\t// CRITICAL: Always verify and truncate to terminal width.\n\t\t// This is the final safeguard against width overflow which would crash the TUI.\n\t\t// Width tracking can drift from actual visible width due to:\n\t\t// - Complex ANSI/OSC sequences (hyperlinks, colors)\n\t\t// - Wide characters at segment boundaries\n\t\t// - Edge cases in segment extraction\n\t\tconst resultWidth = visibleWidth(result);\n\t\tif (resultWidth <= totalWidth) {\n\t\t\treturn result;\n\t\t}\n\t\t// Truncate with strict=true to ensure we don't exceed totalWidth\n\t\treturn sliceByColumn(result, 0, totalWidth, true);\n\t}\n\n\t/**\n\t * Find and extract cursor position from rendered lines.\n\t * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.\n\t * Only scans the bottom terminal height lines (visible viewport).\n\t * @param lines - Rendered lines to search\n\t * @param height - Terminal height (visible viewport size)\n\t * @returns Cursor position { row, col } or null if no marker found\n\t */\n\tprivate extractCursorPosition(lines: string[], height: number): { row: number; col: number } | null {\n\t\t// Only scan the bottom `height` lines (visible viewport)\n\t\tconst viewportTop = Math.max(0, lines.length - height);\n\t\tfor (let row = lines.length - 1; row >= viewportTop; row--) {\n\t\t\tconst line = lines[row];\n\t\t\tconst markerIndex = line.indexOf(CURSOR_MARKER);\n\t\t\tif (markerIndex !== -1) {\n\t\t\t\t// Calculate visual column (width of text before marker)\n\t\t\t\tconst beforeMarker = line.slice(0, markerIndex);\n\t\t\t\tconst col = visibleWidth(beforeMarker);\n\n\t\t\t\t// Strip marker from the line\n\t\t\t\tlines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);\n\n\t\t\t\treturn { row, col };\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate renderingSuspended = false;\n\n\tsuspendRendering(): void {\n\t\tthis.renderingSuspended = true;\n\t\tif (this.renderTimer) {\n\t\t\tclearTimeout(this.renderTimer);\n\t\t\tthis.renderTimer = undefined;\n\t\t}\n\t\tthis.renderRequested = false;\n\t}\n\n\tresumeRendering(): void {\n\t\tthis.renderingSuspended = false;\n\t\tthis.requestRender(true);\n\t}\n\n\tprivate doRender(): void {\n\t\tif (this.stopped || this.renderingSuspended) return;\n\t\tconst width = this.terminal.columns;\n\t\tconst height = this.terminal.rows;\n\n\t\t// Render all children to get full content\n\t\tconst childLines: string[][] = [];\n\t\tfor (const child of this.children) {\n\t\t\tchildLines.push(child.render(width));\n\t\t}\n\n\t\t// Split children into scrollable (top) and fixed (bottom)\n\t\t// The fixedBottomCount property determines how many trailing children\n\t\t// are always pinned to the bottom of the screen\n\t\tconst fixedCount = this.fixedBottomCount;\n\t\tconst scrollableLines: string[] = [];\n\t\tconst fixedLines: string[] = [];\n\t\tfor (let i = 0; i < childLines.length; i++) {\n\t\t\tif (i >= childLines.length - fixedCount) {\n\t\t\t\tfixedLines.push(...childLines[i]);\n\t\t\t} else {\n\t\t\t\tscrollableLines.push(...childLines[i]);\n\t\t\t}\n\t\t}\n\n\t\t// Calculate available space for scrollable area\n\t\tconst fixedHeight = fixedLines.length;\n\t\tconst scrollableViewport = Math.max(0, height - fixedHeight);\n\t\tthis.lastScrollableViewport = scrollableViewport;\n\n\t\t// Apply scrollOffset to scrollable content only\n\t\tconst maxScroll = Math.max(0, scrollableLines.length - scrollableViewport);\n\t\tconst lineCountDelta = scrollableLines.length - this.previousScrollableLineCount;\n\t\tif (lineCountDelta > 0) {\n\t\t\tif (this.autoFollow) {\n\t\t\t\tthis.scrollOffset = 0;\n\t\t\t} else if (this.scrollOffset > 0) {\n\t\t\t\tthis.scrollOffset += lineCountDelta;\n\t\t\t}\n\t\t}\n\t\tif (this.scrollOffset > maxScroll) this.scrollOffset = maxScroll;\n\t\tthis.previousScrollableLineCount = scrollableLines.length;\n\n\t\t// Cache full lines (pre-overlay, pre-highlight) for selection text extraction\n\t\t// and absolute-row coordinate mapping\n\t\tthis.currentFullLines = [...scrollableLines, ...fixedLines];\n\t\tthis.currentScrollableLinesLength = scrollableLines.length;\n\n\t\t// Determine visible scrollable lines\n\t\tconst scrollableViewportTop = Math.max(0, scrollableLines.length - scrollableViewport - this.scrollOffset);\n\t\tconst visibleScrollable = scrollableLines.slice(\n\t\t\tscrollableViewportTop,\n\t\t\tscrollableViewportTop + scrollableViewport,\n\t\t);\n\n\t\t// Combine: visible scrollable content + fixed bottom content\n\t\tlet newLines: string[] = [...visibleScrollable, ...fixedLines];\n\n\t\t// Pad to fill screen height if content is shorter\n\t\twhile (newLines.length < height) newLines.push(\"\");\n\n\t\t// Truncate to screen height\n\t\tnewLines = newLines.slice(0, height);\n\n\t\t// Composite overlays (clear stale layout cache first, then let compositeOverlays refill it)\n\t\tthis.renderedOverlayLayouts = [];\n\t\tif (this.overlayStack.length > 0) {\n\t\t\tnewLines = this.compositeOverlays([...newLines], width, height);\n\t\t}\n\n\t\t// Cache composited lines (post-overlay, pre-highlight) for overlay text extraction\n\t\tthis.currentCompositedLines = [...newLines];\n\n\t\tconst cursorPos = this.extractCursorPosition(newLines, height);\n\t\tnewLines = this.applyLineResets(newLines);\n\n\t\t// Update viewport-top state before selection highlight, so bufferToScreenRow\n\t\t// inside applySelectionHighlight uses the correct viewport offset.\n\t\tthis.currentScrollableViewportTop = scrollableViewportTop;\n\n\t\t// Selection highlight: buffer-absolute row iteration via bufferToScreenRow\n\t\tthis.applySelectionHighlight(newLines, height);\n\n\t\tconst renderChanged = (): void => {\n\t\t\tthis.fullRedrawCount += 1;\n\t\t\t// Sync mode + cursor home + sequential line output (no full screen clear).\n\t\t\t// \\x1b[?2026h defers display until \\x1b[?2026l for atomic update.\n\t\t\t// \\x1b[K clears to end-of-line after each line to remove residual content\n\t\t\t// from previous renders, replacing the flicker-causing \\x1b[2J clear screen.\n\t\t\t// Uses sequential \\r\\n output (like the original) for minimal bandwidth.\n\t\t\tlet buffer = `\\x1b[?2026h${TUI.CURSOR_HIDE_PREFIX}\\x1b[H`;\n\t\t\tbuffer += this.deleteKittyImages(this.previousKittyImageIds);\n\t\t\tfor (let i = 0; i < newLines.length; i++) {\n\t\t\t\tif (i > 0) buffer += \"\\r\\n\";\n\t\t\t\tbuffer += newLines[i];\n\t\t\t\tbuffer += \"\\x1b[K\";\n\t\t\t}\n\t\t\tbuffer += this.buildHardwareCursorSequence(cursorPos, newLines.length);\n\t\t\tbuffer += \"\\x1b[?2026l\";\n\t\t\tthis.terminal.write(buffer);\n\t\t\tthis.cursorRow = Math.max(0, newLines.length - 1);\n\t\t\tthis.maxLinesRendered = newLines.length;\n\t\t\tthis.previousViewportTop = scrollableViewportTop;\n\t\t\tthis.previousLines = newLines;\n\t\t\tthis.previousKittyImageIds = this.collectKittyImageIds(newLines);\n\t\t\tthis.previousWidth = width;\n\t\t\tthis.previousHeight = height;\n\t\t};\n\n\t\tconst widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;\n\t\tconst heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;\n\n\t\tif (this.previousLines.length === 0) {\n\t\t\trenderChanged();\n\t\t\treturn;\n\t\t}\n\n\t\tif (widthChanged || (heightChanged && !isTermuxSession())) {\n\t\t\trenderChanged();\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.clearOnShrink && newLines.length < this.maxLinesRendered && this.overlayStack.length === 0) {\n\t\t\trenderChanged();\n\t\t\treturn;\n\t\t}\n\n\t\tlet firstChanged = -1;\n\t\tlet lastChanged = -1;\n\t\tconst maxLines = Math.max(newLines.length, this.previousLines.length);\n\t\tfor (let i = 0; i < maxLines; i++) {\n\t\t\tconst oldLine = i < this.previousLines.length ? this.previousLines[i] : \"\";\n\t\t\tconst newLine = i < newLines.length ? newLines[i] : \"\";\n\t\t\tif (oldLine !== newLine) {\n\t\t\t\tif (firstChanged === -1) firstChanged = i;\n\t\t\t\tlastChanged = i;\n\t\t\t}\n\t\t}\n\t\tif (newLines.length > this.previousLines.length) {\n\t\t\tif (firstChanged === -1) firstChanged = this.previousLines.length;\n\t\t\tlastChanged = newLines.length - 1;\n\t\t}\n\t\tif (firstChanged !== -1) lastChanged = this.expandLastChangedForKittyImages(firstChanged, lastChanged);\n\n\t\tif (firstChanged === -1) {\n\t\t\t// No content changed, but cursor position may have — wrap in\n\t\t\t// sync mode so the cursor move is atomic with the frame.\n\t\t\tconst seq = this.buildHardwareCursorSequence(cursorPos, newLines.length);\n\t\t\tthis.terminal.write(`\\x1b[?2026h${TUI.CURSOR_HIDE_PREFIX}${seq}\\x1b[?2026l`);\n\t\t\tthis.previousViewportTop = scrollableViewportTop;\n\t\t\tthis.previousHeight = height;\n\t\t\treturn;\n\t\t}\n\n\t\t// If >50% of visible lines changed, do a full re-render (more efficient than incremental)\n\t\tif (lastChanged - firstChanged + 1 > height * 0.5 || firstChanged < 0) {\n\t\t\trenderChanged();\n\t\t\treturn;\n\t\t}\n\n\t\t// All changes are in deleted lines (nothing to render, just clear)\n\t\tif (firstChanged >= newLines.length) {\n\t\t\tif (this.previousLines.length > newLines.length) {\n\t\t\t\tlet buffer = \"\\x1b[?2026h\";\n\t\t\t\tbuffer += this.deleteChangedKittyImages(firstChanged, lastChanged);\n\t\t\t\t// Move to end of new content (clamp to 0 for empty content)\n\t\t\t\tconst targetRow = Math.max(0, newLines.length - 1);\n\t\t\t\tif (targetRow < this.previousViewportTop) {\n\t\t\t\t\trenderChanged();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst lineDiff = targetRow - this.hardwareCursorRow;\n\t\t\t\tif (lineDiff > 0) buffer += `\\x1b[${lineDiff}B`;\n\t\t\t\telse if (lineDiff < 0) buffer += `\\x1b[${-lineDiff}A`;\n\t\t\t\tbuffer += \"\\r\";\n\t\t\t\t// Clear extra lines without scrolling\n\t\t\t\tconst extraLines = this.previousLines.length - newLines.length;\n\t\t\t\tif (extraLines > height) {\n\t\t\t\t\trenderChanged();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst clearStartOffset = newLines.length === 0 ? 0 : 1;\n\t\t\t\tif (extraLines > 0 && clearStartOffset > 0) {\n\t\t\t\t\tbuffer += `\\x1b[${clearStartOffset}B`;\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < extraLines; i++) {\n\t\t\t\t\tbuffer += \"\\r\\x1b[2K\";\n\t\t\t\t\tif (i < extraLines - 1) buffer += \"\\x1b[1B\";\n\t\t\t\t}\n\t\t\t\tconst moveBack = Math.max(0, extraLines - 1 + clearStartOffset);\n\t\t\t\tif (moveBack > 0) {\n\t\t\t\t\tbuffer += `\\x1b[${moveBack}A`;\n\t\t\t\t}\n\t\t\t\tbuffer += \"\\x1b[?2026l\";\n\t\t\t\tthis.terminal.write(buffer);\n\t\t\t\tthis.cursorRow = targetRow;\n\t\t\t\tthis.hardwareCursorRow = targetRow;\n\t\t\t}\n\t\t\tthis.terminal.write(this.buildHardwareCursorSequence(cursorPos, newLines.length));\n\t\t\tthis.previousLines = newLines;\n\t\t\tthis.previousKittyImageIds = this.collectKittyImageIds(newLines);\n\t\t\tthis.previousWidth = width;\n\t\t\tthis.previousHeight = height;\n\t\t\tthis.previousViewportTop = scrollableViewportTop;\n\t\t\treturn;\n\t\t}\n\n\t\tlet buffer = `\\x1b[?2026h${TUI.CURSOR_HIDE_PREFIX}`;\n\t\tbuffer += this.deleteChangedKittyImages(firstChanged, lastChanged);\n\t\tconst renderEnd = Math.min(lastChanged, newLines.length - 1);\n\t\tfor (let i = firstChanged; i <= renderEnd; i++) {\n\t\t\tbuffer += `\\x1b[${i + 1};1H\\x1b[2K\\x1b[0m${newLines[i]}`;\n\t\t}\n\t\tif (newLines.length < this.previousLines.length) {\n\t\t\tfor (let i = newLines.length; i < this.previousLines.length; i++) {\n\t\t\t\tbuffer += `\\x1b[${i + 1};1H\\x1b[2K`;\n\t\t\t}\n\t\t}\n\t\tbuffer += this.buildHardwareCursorSequence(cursorPos, newLines.length);\n\t\tbuffer += \"\\x1b[?2026l\";\n\t\tthis.terminal.write(buffer);\n\t\tthis.cursorRow = Math.max(0, newLines.length - 1);\n\t\tthis.previousLines = newLines;\n\t\tthis.previousKittyImageIds = this.collectKittyImageIds(newLines);\n\t\tthis.previousWidth = width;\n\t\tthis.previousHeight = height;\n\t\tthis.previousViewportTop = scrollableViewportTop;\n\t}\n\n\t/**\n\t * Build escape sequences for positioning the hardware cursor.\n\t * Returned string should be appended to the render buffer *before*\n\t * the sync-mode terminator (\\x1b[?2026l) so the cursor state change\n\t * is atomic with the content update and never causes a visible flash.\n\t * @param cursorPos The cursor position extracted from rendered output, or null\n\t * @param totalLines Total number of rendered lines\n\t */\n\tprivate buildHardwareCursorSequence(cursorPos: { row: number; col: number } | null, totalLines: number): string {\n\t\tif (!cursorPos || totalLines <= 0) {\n\t\t\treturn \"\\x1b[?25l\";\n\t\t}\n\n\t\tconst targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));\n\t\tconst targetCol = Math.max(0, cursorPos.col);\n\n\t\tthis.hardwareCursorRow = targetRow;\n\n\t\tif (this.showHardwareCursor) {\n\t\t\t// DECSCUSR Ps=6: steady bar cursor — non-blinking, unobtrusive,\n\t\t\t// and ensures IME frameworks track the cursor position reliably.\n\t\t\treturn `\\x1b[${targetRow + 1};${targetCol + 1}H\\x1b[6 q\\x1b[?25h`;\n\t\t}\n\t\t// Hide then move — both inside the sync-mode buffer so the\n\t\t// terminal never shows the cursor at an intermediate position.\n\t\treturn `\\x1b[?25l\\x1b[${targetRow + 1};${targetCol + 1}H`;\n\t}\n\n\t/**\n\t * Cursor-hide prefix to place at the start of every render buffer,\n\t * before any content updates. Guarantees the hardware cursor is\n\t * invisible before the terminal processes line changes, which\n\t * prevents the cursor from briefly appearing at stale positions\n\t * on terminals with imperfect sync-mode support.\n\t */\n\tprivate static readonly CURSOR_HIDE_PREFIX = \"\\x1b[?25l\";\n}\n"]}
|