返回源码地图

packages/tui/src/tui.ts

v1.3.0 · 71023aec1546 · 10:Component契约与共享UI抽象;非完整终端渲染审计

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1/**
2 * Minimal TUI implementation with differential rendering
3 */
4
5import { performance } from "node:perf_hooks";
6import { isKeyRelease, matchesKey } from "./keys.ts";
7import type { Terminal } from "./terminal.ts";
8import {
9 parseOscColorResponse,
10 parseTerminalColorSchemeReport,
11 type RgbColor,
12 type TerminalColorScheme,
13 type TerminalColors,
14} from "./terminal-colors.ts";
15import { getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.ts";
16import { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, visibleWidth } from "./utils.ts";
17
18/**
19 * Component interface - all components must implement this
20 */
21export type TuiMouseEventType = "press" | "release" | "move" | "drag" | "click" | "wheel";
22export type TuiMouseButton = "left" | "middle" | "right" | "none";
23
24/** Normalized cell-based mouse event. Coordinates are zero-based. */
25export interface TuiMouseEvent {
26 type: TuiMouseEventType;
27 button: TuiMouseButton;
28 /** Coordinates local to the receiving component. */
29 x: number;
30 y: number;
31 /** Absolute terminal coordinates. */
32 screenX: number;
33 screenY: number;
34 /** Current component bounds. */
35 width: number;
36 height: number;
37 shift: boolean;
38 alt: boolean;
39 ctrl: boolean;
40 /** Logical lines. Negative values scroll up. */
41 wheelDelta?: number;
42 /** Consecutive click count when type is click. */
43 clickCount?: number;
44}
45
46export interface TuiMouseEventResult {
47 /** Stop propagation and suppress renderer-level fallback behavior. */
48 handled?: boolean;
49 /** Route subsequent drag/release events to this component. Implies handled. */
50 capture?: boolean;
51 /** Give keyboard focus to this component. Implies handled. */
52 focus?: boolean;
53 /**
54 * Explicitly request or suppress a render. Move and release default to false;
55 * press, click, drag, and wheel default to true.
56 */
57 render?: boolean;
58}
59
60/** Internal target metadata used by containers and alternate-screen dispatch. */
61export interface TuiMouseDispatchTarget {
62 component: Component;
63 originX: number;
64 originY: number;
65 width: number;
66 height: number;
67}
68
69/** Result of dispatching to a concrete component. */
70export interface TuiMouseDispatchResult extends TuiMouseEventResult {
71 handled: true;
72 target: TuiMouseDispatchTarget;
73 /** Keyboard focus target, which may be a delegating parent container. */
74 focusTarget?: Component;
75}
76
77/**
78 * Dispatch an event to a component and retain the exact target and coordinate
79 * transform. Containers use this when forwarding events to nested children.
80 */
81export function dispatchMouseEvent(component: Component, event: TuiMouseEvent): TuiMouseDispatchResult | undefined {
82 const result = component.handleMouse?.(event);
83 if (!result) return undefined;
84 if ("target" in result) {
85 // The component forwarded the event to a child it hosts. Like a delegating container, it routes
86 // keys to that child itself, so it keeps keyboard focus. Focusing the child directly would leave
87 // focus on a detached component once the host removes it, e.g. a closed settings submenu.
88 const forwarded = result as TuiMouseDispatchResult;
89 return forwarded.focus && component.handleInput ? { ...forwarded, focusTarget: component } : forwarded;
90 }
91 if (!result.handled && !result.capture && !result.focus) return undefined;
92 return {
93 ...result,
94 handled: true,
95 ...(result.focus ? { focusTarget: component } : {}),
96 target: {
97 component,
98 originX: event.screenX - event.x,
99 originY: event.screenY - event.y,
100 width: event.width,
101 height: event.height,
102 },
103 };
104}
105
106/** Recreate local coordinates for a previously dispatched mouse target. */
107export function retargetMouseEvent(event: TuiMouseEvent, target: TuiMouseDispatchTarget): TuiMouseEvent {
108 return {
109 ...event,
110 x: event.screenX - target.originX,
111 y: event.screenY - target.originY,
112 width: target.width,
113 height: target.height,
114 };
115}
116
117export interface Component {
118 /**
119 * Render the component to lines for the given viewport width
120 * @param width - Current viewport width
121 * @returns Array of strings, each representing a line
122 */
123 render(width: number): string[];
124
125 /** Optional handler for keyboard input when component has focus. */
126 handleInput?(data: string): void;
127
128 /** Optional normalized mouse handler. */
129 handleMouse?(event: TuiMouseEvent): TuiMouseEventResult | undefined;
130
131 /**
132 * If true, component receives key release events (Kitty protocol).
133 * Default is false - release events are filtered out.
134 */
135 wantsKeyRelease?: boolean;
136
137 /**
138 * Invalidate any cached rendering state.
139 * Called when theme changes or when component needs to re-render from scratch.
140 */
141 invalidate(): void;
142}
143
144export type TuiInputListenerResult = { consume?: boolean; data?: string } | undefined;
145export type TuiInputListener = (data: string) => TuiInputListenerResult;
146type PendingTerminalColorQuery = {
147 foreground?: RgbColor;
148 background?: RgbColor;
149 palette: Array<RgbColor | undefined>;
150 /** Targets that already replied, so duplicates do not count twice. */
151 replied: Set<string>;
152 /**
153 * Receives the result: the promise's resolve until the timeout, then `onLateReply`. Unset once the
154 * query completed (on the DA1 reply or once every color replied); later replies are ignored.
155 */
156 deliver: ((colors: TerminalColors) => void) | undefined;
157 timer: NodeJS.Timeout | undefined;
158};
159
160const TERMINAL_PALETTE_SIZE = 16;
161/** OSC 10 and 11 plus OSC 4 for every palette color. */
162const TERMINAL_COLOR_REPLY_COUNT = 2 + TERMINAL_PALETTE_SIZE;
163/**
164 * Default colors, palette colors 0-15, and a trailing primary device attributes (DA1) request.
165 * Every terminal answers DA1 and terminals answer in order, so the DA1 reply marks the end of
166 * the color replies, including for terminals that ignore the color queries.
167 */
168const TERMINAL_COLOR_QUERY = `\x1b]10;?\x07\x1b]11;?\x07${Array.from(
169 { length: TERMINAL_PALETTE_SIZE },
170 (_, index) => `\x1b]4;${index};?\x07`,
171).join("")}\x1b[c`;
172const DEVICE_ATTRIBUTES_RESPONSE_PATTERN = /^\x1b\[\?[\d;]*c$/;
173
174/**
175 * Interface for components that can receive focus and display a hardware cursor.
176 * When focused, the component should emit CURSOR_MARKER at the cursor position
177 * in its render output. TUI will find this marker and position the hardware
178 * cursor there for proper IME candidate window positioning.
179 */
180export interface Focusable {
181 /** Set by TUI when focus changes. Component should emit CURSOR_MARKER when true. */
182 focused: boolean;
183}
184
185/** Type guard to check if a component implements Focusable */
186export function isFocusable(component: Component | null): component is Component & Focusable {
187 return component !== null && "focused" in component;
188}
189
190/**
191 * Cursor position marker - APC (Application Program Command) sequence.
192 * This is a zero-width escape sequence that terminals ignore.
193 * Components emit this at the cursor position when focused.
194 * TUI finds and strips this marker, then positions the hardware cursor there.
195 */
196export const CURSOR_MARKER = "\x1b_pi:c\x07";
197
198/** Fake cursor markers - zero-width APC sequences around the text drawn as the cursor. See resolveFakeCursors(). */
199export const FAKE_CURSOR_START = "\x1b_pi:fc\x07";
200export const FAKE_CURSOR_END = "\x1b_pi:/fc\x07";
201// CURSOR_MARKER + FAKE_CURSOR_START + text + FAKE_CURSOR_END. Truncating the line right after the cursor cell drops the end.
202const FOCUSED_FAKE_CURSOR = /(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;
203
204/** Wrap text in fake cursor markers. */
205export function renderFakeCursor(text: string): string {
206 return `${FAKE_CURSOR_START}${text}${FAKE_CURSOR_END}`;
207}
208
209export { visibleWidth };
210
211/**
212 * Anchor position for overlays
213 */
214export type OverlayAnchor =
215 | "center"
216 | "top-left"
217 | "top-right"
218 | "bottom-left"
219 | "bottom-right"
220 | "top-center"
221 | "bottom-center"
222 | "left-center"
223 | "right-center";
224
225/**
226 * Margin configuration for overlays
227 */
228export interface OverlayMargin {
229 top?: number;
230 right?: number;
231 bottom?: number;
232 left?: number;
233}
234
235/** Value that can be absolute (number) or percentage (string like "50%") */
236export type SizeValue = number | `${number}%`;
237
238/** Parse a SizeValue into absolute value given a reference size */
239function parseSizeValue(value: SizeValue | undefined, referenceSize: number): number | undefined {
240 if (value === undefined) return undefined;
241 if (typeof value === "number") return value;
242 // Parse percentage string like "50%"
243 const match = value.match(/^(\d+(?:\.\d+)?)%$/);
244 if (match) {
245 return Math.floor((referenceSize * parseFloat(match[1])) / 100);
246 }
247 return undefined;
248}
249
250/**
251 * Options for overlay positioning and sizing.
252 * Values can be absolute numbers or percentage strings (e.g., "50%").
253 */
254export interface OverlayOptions {
255 // === Sizing ===
256 /** Width in columns, or percentage of terminal width (e.g., "50%") */
257 width?: SizeValue;
258 /** Minimum width in columns */
259 minWidth?: number;
260 /** Maximum height in rows, or percentage of terminal height (e.g., "50%") */
261 maxHeight?: SizeValue;
262
263 // === Positioning - anchor-based ===
264 /** Anchor point for positioning (default: 'center') */
265 anchor?: OverlayAnchor;
266 /** Horizontal offset from anchor position (positive = right) */
267 offsetX?: number;
268 /** Vertical offset from anchor position (positive = down) */
269 offsetY?: number;
270
271 // === Positioning - percentage or absolute ===
272 /** Row position: absolute number, or percentage (e.g., "25%" = 25% from top) */
273 row?: SizeValue;
274 /** Column position: absolute number, or percentage (e.g., "50%" = centered horizontally) */
275 col?: SizeValue;
276
277 // === Margin from terminal edges ===
278 /** Margin from terminal edges. Number applies to all sides. */
279 margin?: OverlayMargin | number;
280
281 // === Visibility ===
282 /**
283 * Control overlay visibility based on terminal dimensions.
284 * If provided, overlay is only rendered when this returns true.
285 * Called each render cycle with current terminal dimensions.
286 */
287 visible?: (termWidth: number, termHeight: number) => boolean;
288 /** If true, don't capture keyboard focus when shown */
289 nonCapturing?: boolean;
290}
291
292/** Options for {@link OverlayHandle.unfocus}. */
293export interface OverlayUnfocusOptions {
294 /** Explicit target to focus after releasing this overlay. */
295 target: Component | null;
296}
297
298/** Last rendered terminal-relative overlay rectangle. */
299export interface OverlayBounds {
300 row: number;
301 col: number;
302 width: number;
303 height: number;
304}
305
306/**
307 * Handle returned by showOverlay for controlling the overlay
308 */
309export interface OverlayHandle {
310 /** Permanently remove the overlay (cannot be shown again) */
311 hide(): void;
312 /** Temporarily hide or show the overlay */
313 setHidden(hidden: boolean): void;
314 /** Check if overlay is temporarily hidden */
315 isHidden(): boolean;
316 /** Focus this overlay and bring it to the visual front */
317 focus(): void;
318 /** Release focus to the next visible capturing overlay or previous target, or to an explicit target when provided */
319 unfocus(options?: OverlayUnfocusOptions): void;
320 /** Check if this overlay currently has focus */
321 isFocused(): boolean;
322 /** Get the most recent rendered bounds for a visible overlay. */
323 getBounds(): OverlayBounds | undefined;
324}
325
326type OverlayStackEntry = {
327 component: Component;
328 options?: OverlayOptions;
329 preFocus: Component | null;
330 hidden: boolean;
331 focusOrder: number;
332 bounds?: OverlayBounds;
333};
334
335type RenderedOverlayLayout = {
336 entry: OverlayStackEntry;
337 row: number;
338 col: number;
339 width: number;
340 height: number;
341};
342
343type OverlayBlockedFocusResume = { status: "restore-overlay" } | { status: "focus-target"; target: Component | null };
344type EligibleOverlayFocusRestoreState = { status: "eligible"; overlay: OverlayStackEntry };
345type BlockedOverlayFocusRestoreState = {
346 status: "blocked";
347 overlay: OverlayStackEntry;
348 blockedBy: Component;
349 resume: OverlayBlockedFocusResume;
350};
351type ActiveOverlayFocusRestoreState = EligibleOverlayFocusRestoreState | BlockedOverlayFocusRestoreState;
352type OverlayFocusRestoreState = { status: "inactive" } | ActiveOverlayFocusRestoreState;
353type OverlayFocusRestorePolicy = "clear" | "preserve";
354
355/**
356 * Container - a component that contains other components
357 */
358export class Container implements Component {
359 children: Component[] = [];
360 private mouseLayout?: { width: number; children: Array<{ component: Component; height: number }> };
361
362 addChild(component: Component): void {
363 this.children.push(component);
364 }
365
366 removeChild(component: Component): void {
367 const index = this.children.indexOf(component);
368 if (index !== -1) {
369 this.children.splice(index, 1);
370 }
371 }
372
373 clear(): void {
374 this.children = [];
375 }
376
377 invalidate(): void {
378 for (const child of this.children) {
379 child.invalidate?.();
380 }
381 }
382
383 handleMouse(event: TuiMouseEvent): TuiMouseDispatchResult | undefined {
384 if (event.y < 0 || event.y >= event.height) return undefined;
385 const mouseChildren =
386 this.mouseLayout?.width === event.width
387 ? this.mouseLayout.children
388 : this.children.map((component) => ({ component, height: component.render(event.width).length }));
389 let childY = 0;
390 for (const { component: child, height: childHeight } of mouseChildren) {
391 if (event.y >= childY && event.y < childY + childHeight) {
392 const result = dispatchMouseEvent(child, {
393 ...event,
394 y: event.y - childY,
395 height: childHeight,
396 });
397 if (result?.focus && (this as Component).handleInput) return { ...result, focusTarget: this };
398 return result;
399 }
400 childY += childHeight;
401 }
402 return undefined;
403 }
404
405 render(width: number): string[] {
406 const lines: string[] = [];
407 const mouseChildren: Array<{ component: Component; height: number }> = [];
408 for (const child of this.children) {
409 const childLines = child.render(width);
410 mouseChildren.push({ component: child, height: childLines.length });
411 for (const line of childLines) {
412 lines.push(line);
413 }
414 }
415 this.mouseLayout = { width, children: mouseChildren };
416 return lines;
417 }
418}
419
420/**
421 * TUI - Main class for managing terminal UI with differential rendering
422 */
423const SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07";
424
425/** Composite overlay content into a terminal line at a fixed column. */
426export function compositeTuiLine(
427 baseLine: string,
428 overlayLine: string,
429 startCol: number,
430 overlayWidth: number,
431 totalWidth: number,
432): string {
433 if (isImageLine(baseLine)) return baseLine;
434
435 const afterStart = startCol + overlayWidth;
436 const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
437 const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
438 const beforePad = Math.max(0, startCol - base.beforeWidth);
439 const overlayPad = Math.max(0, overlayWidth - overlay.width);
440 const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
441 const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
442 const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
443 const afterPad = Math.max(0, afterTarget - base.afterWidth);
444 const result =
445 base.before +
446 " ".repeat(beforePad) +
447 SEGMENT_RESET +
448 overlay.text +
449 " ".repeat(overlayPad) +
450 SEGMENT_RESET +
451 base.after +
452 " ".repeat(afterPad);
453
454 return visibleWidth(result) <= totalWidth ? result : sliceByColumn(result, 0, totalWidth, true);
455}
456
457export type TuiMode = "regular" | "fullscreen";
458
459export interface TuiStopOptions {
460 /** Leave renderer output in place for another TUI taking over the same terminal. */
461 preserveScreen?: boolean;
462}
463
464export interface TUI extends Component {
465 readonly mode: TuiMode;
466 children: Component[];
467 terminal: Terminal;
468 onDebug?: () => void;
469 readonly fullRedraws: number;
470 addChild(component: Component): void;
471 removeChild(component: Component): void;
472 clear(): void;
473 getShowHardwareCursor(): boolean;
474 setShowHardwareCursor(enabled: boolean): void;
475 getClearOnShrink(): boolean;
476 setClearOnShrink(enabled: boolean): void;
477 setFocus(component: Component | null): void;
478 showOverlay(component: Component, options?: OverlayOptions): OverlayHandle;
479 hideOverlay(): void;
480 hasOverlay(): boolean;
481 start(): void;
482 stop(options?: TuiStopOptions): void;
483 renderNow(force?: boolean): void;
484 requestRender(force?: boolean): void;
485 addInputListener(listener: TuiInputListener): () => void;
486 removeInputListener(listener: TuiInputListener): void;
487 onTerminalColorSchemeChange(listener: (scheme: TerminalColorScheme) => void): () => void;
488 setTerminalColorSchemeNotifications(enabled: boolean): void;
489 queryTerminalColors(options: {
490 timeoutMs: number;
491 onLateReply?: (colors: TerminalColors) => void;
492 }): Promise<TerminalColors>;
493}
494
495export const VIEWPORT_TUI = Symbol.for("@earendil-works/pi-tui/viewport");
496
497export interface ViewportTUI extends TUI {
498 readonly [VIEWPORT_TUI]: true;
499 setLayoutRoot(component: Component | undefined): void;
500}
501
502export function isViewportTUI(tui: TUI): tui is ViewportTUI {
503 return (tui as Partial<ViewportTUI>)[VIEWPORT_TUI] === true;
504}
505
506export abstract class TuiBase extends Container implements TUI {
507 abstract readonly mode: TuiMode;
508 public terminal: Terminal;
509 private focusedComponent: Component | null = null;
510 private inputListeners = new Set<TuiInputListener>();
511
512 /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
513 public onDebug?: () => void;
514 private renderRequested = false;
515 private immediateRenderScheduled = false;
516 private renderTimer: NodeJS.Timeout | undefined;
517 private lastRenderAt = 0;
518 private static readonly MIN_RENDER_INTERVAL_MS = 16;
519 private showHardwareCursor = false;
520 private clearOnShrink = false;
521 protected fullRedrawCount = 0;
522 protected stopped = false;
523 /**
524 * Color queries waiting for their DA1 reply, oldest first. Terminals answer in order, so color
525 * replies belong to the oldest one. Queries stay here after a timeout to collect late replies.
526 */
527 private pendingTerminalColorQueries: PendingTerminalColorQuery[] = [];
528 private terminalColorSchemeListeners = new Set<(scheme: TerminalColorScheme) => void>();
529 private terminalColorSchemeNotificationsEnabled = false;
530 /** Directory for debug/crash logs. When undefined, debug logging is disabled and crash dumps fall back to the OS temp directory. */
531 protected readonly logDirectory: string | undefined;
532
533 // Overlay stack for modal components rendered on top of base content
534 private focusOrderCounter = 0;
535 private overlayStack: OverlayStackEntry[] = [];
536 private renderedOverlayLayouts: RenderedOverlayLayout[] = [];
537
538 get hasOverlayEntries(): boolean {
539 return this.overlayStack.length > 0;
540 }
541 private overlayFocusRestore: OverlayFocusRestoreState = { status: "inactive" };
542
543 constructor(terminal: Terminal, showHardwareCursor?: boolean, logDirectory?: string) {
544 super();
545 this.terminal = terminal;
546 this.logDirectory = logDirectory;
547 if (showHardwareCursor !== undefined) {
548 this.showHardwareCursor = showHardwareCursor;
549 }
550 }
551
552 protected abstract doRender(): void;
553
554 protected resetRenderState(): void {}
555
556 protected beforeTerminalStart(): void {}
557
558 protected afterTerminalStart(): void {}
559
560 protected beforeTerminalStop(_options: TuiStopOptions): void {}
561
562 protected afterTerminalStop(_options: TuiStopOptions): void {}
563
564 get fullRedraws(): number {
565 return this.fullRedrawCount;
566 }
567
568 getShowHardwareCursor(): boolean {
569 return this.showHardwareCursor;
570 }
571
572 setShowHardwareCursor(enabled: boolean): void {
573 if (this.showHardwareCursor === enabled) return;
574 this.showHardwareCursor = enabled;
575 if (!enabled) {
576 this.hideTerminalCursor();
577 }
578 this.requestRender();
579 }
580
581 getClearOnShrink(): boolean {
582 return this.clearOnShrink;
583 }
584
585 /**
586 * Set whether to trigger full re-render when content shrinks.
587 * When true, empty rows are cleared when content shrinks.
588 * When false (default), empty rows remain (reduces redraws on slower terminals).
589 */
590 setClearOnShrink(enabled: boolean): void {
591 this.clearOnShrink = enabled;
592 }
593
594 getFocusedComponent(): Component | null {
595 return this.focusedComponent;
596 }
597
598 setFocus(component: Component | null): void {
599 this.setFocusInternal({ component, overlayFocusRestore: "clear" });
600 }
601
602 private setFocusInternal({
603 component,
604 overlayFocusRestore,
605 }: {
606 component: Component | null;
607 overlayFocusRestore: OverlayFocusRestorePolicy;
608 }): void {
609 const previousFocus = this.focusedComponent;
610 let nextFocus = component;
611 const previousFocusedOverlay = previousFocus
612 ? this.overlayStack.find((entry) => entry.component === previousFocus && this.isOverlayVisible(entry))
613 : undefined;
614 const nextFocusIsOverlay = nextFocus ? this.overlayStack.some((entry) => entry.component === nextFocus) : false;
615 const restoreState = this.getVisibleOverlayFocusRestore();
616 if (nextFocus && !nextFocusIsOverlay) {
617 if (restoreState.status === "blocked" && restoreState.blockedBy === previousFocus) {
618 if (restoreState.resume.status === "focus-target" || !this.isComponentMounted(restoreState.blockedBy)) {
619 nextFocus = this.resolveBlockedOverlayFocusResume(restoreState);
620 } else {
621 this.overlayFocusRestore = {
622 status: "blocked",
623 overlay: restoreState.overlay,
624 blockedBy: nextFocus,
625 resume: restoreState.resume,
626 };
627 }
628 } else if (
629 previousFocusedOverlay &&
630 restoreState.status !== "inactive" &&
631 restoreState.overlay === previousFocusedOverlay &&
632 !this.isOverlayFocusAncestor(previousFocusedOverlay, nextFocus)
633 ) {
634 this.overlayFocusRestore = {
635 status: "blocked",
636 overlay: previousFocusedOverlay,
637 blockedBy: nextFocus,
638 resume: { status: "restore-overlay" },
639 };
640 }
641 } else if (nextFocus === null) {
642 if (restoreState.status === "blocked" && restoreState.blockedBy === previousFocus) {
643 nextFocus = this.resolveBlockedOverlayFocusResume(restoreState);
644 } else if (overlayFocusRestore === "clear") {
645 this.clearOverlayFocusRestore();
646 }
647 }
648
649 if (isFocusable(this.focusedComponent)) {
650 this.focusedComponent.focused = false;
651 }
652
653 this.focusedComponent = nextFocus;
654
655 if (isFocusable(nextFocus)) {
656 nextFocus.focused = true;
657 }
658
659 const focusedOverlay = nextFocus
660 ? this.overlayStack.find((entry) => entry.component === nextFocus && this.isOverlayVisible(entry))
661 : undefined;
662 if (focusedOverlay) {
663 this.overlayFocusRestore = { status: "eligible", overlay: focusedOverlay };
664 }
665 }
666
667 private clearOverlayFocusRestore(): void {
668 this.overlayFocusRestore = { status: "inactive" };
669 }
670
671 private clearOverlayFocusRestoreFor(overlay: OverlayStackEntry): void {
672 if (this.overlayFocusRestore.status !== "inactive" && this.overlayFocusRestore.overlay === overlay) {
673 this.clearOverlayFocusRestore();
674 }
675 }
676
677 private resolveBlockedOverlayFocusResume(restoreState: BlockedOverlayFocusRestoreState): Component | null {
678 if (restoreState.resume.status === "restore-overlay") return restoreState.overlay.component;
679 this.clearOverlayFocusRestore();
680 return restoreState.resume.target;
681 }
682
683 private getVisibleOverlayFocusRestore(): OverlayFocusRestoreState {
684 const restoreState = this.overlayFocusRestore;
685 if (restoreState.status === "inactive") return restoreState;
686 if (!this.overlayStack.includes(restoreState.overlay) || !this.isOverlayVisible(restoreState.overlay)) {
687 return { status: "inactive" };
688 }
689 return restoreState;
690 }
691
692 private isOverlayFocusAncestor(entry: OverlayStackEntry, component: Component): boolean {
693 const visited = new Set<Component>();
694 let current = entry.preFocus;
695 while (current && !visited.has(current)) {
696 visited.add(current);
697 if (current === component) return true;
698 current = this.overlayStack.find((overlay) => overlay.component === current)?.preFocus ?? null;
699 }
700 return false;
701 }
702
703 private retargetOverlayPreFocus(removed: OverlayStackEntry): void {
704 for (const overlay of this.overlayStack) {
705 if (overlay !== removed && overlay.preFocus === removed.component) {
706 overlay.preFocus = removed.preFocus;
707 }
708 }
709 }
710
711 protected getMountedRoots(): readonly Component[] {
712 return this.children;
713 }
714
715 private isComponentMounted(component: Component): boolean {
716 return this.getMountedRoots().some((child) => this.containsComponent(child, component));
717 }
718
719 private containsComponent(root: Component, target: Component): boolean {
720 if (root === target) return true;
721 if (!(root instanceof Container)) return false;
722 return root.children.some((child) => this.containsComponent(child, target));
723 }
724
725 /**
726 * Show an overlay component with configurable positioning and sizing.
727 * Returns a handle to control the overlay's visibility.
728 */
729 showOverlay(component: Component, options?: OverlayOptions): OverlayHandle {
730 const entry: OverlayStackEntry = {
731 component,
732 ...(options === undefined ? {} : { options }),
733 preFocus: this.focusedComponent,
734 hidden: false,
735 focusOrder: ++this.focusOrderCounter,
736 };
737 this.overlayStack.push(entry);
738 // Only focus if overlay is actually visible
739 if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
740 this.setFocus(component);
741 }
742 this.hideTerminalCursor();
743 this.requestRender();
744
745 // Return handle for controlling this overlay
746 return {
747 hide: () => {
748 const index = this.overlayStack.indexOf(entry);
749 if (index !== -1) {
750 this.clearOverlayFocusRestoreFor(entry);
751 this.retargetOverlayPreFocus(entry);
752 this.overlayStack.splice(index, 1);
753 // Restore focus if this overlay had focus
754 if (this.focusedComponent === component) {
755 const topVisible = this.getTopmostVisibleOverlay();
756 this.setFocus(topVisible?.component ?? entry.preFocus);
757 }
758 if (this.overlayStack.length === 0) this.hideTerminalCursor();
759 this.requestRender();
760 }
761 },
762 setHidden: (hidden: boolean) => {
763 if (entry.hidden === hidden) return;
764 entry.hidden = hidden;
765 // Update focus when hiding/showing
766 if (hidden) {
767 this.clearOverlayFocusRestoreFor(entry);
768 // If this overlay had focus, move focus to next visible or preFocus
769 if (this.focusedComponent === component) {
770 const topVisible = this.getTopmostVisibleOverlay();
771 this.setFocus(topVisible?.component ?? entry.preFocus);
772 }
773 } else {
774 // Restore focus to this overlay when showing (if it's actually visible)
775 if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
776 entry.focusOrder = ++this.focusOrderCounter;
777 this.setFocus(component);
778 }
779 }
780 this.requestRender();
781 },
782 isHidden: () => entry.hidden,
783 focus: () => {
784 if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry)) return;
785 entry.focusOrder = ++this.focusOrderCounter;
786 this.setFocus(component);
787 this.requestRender();
788 },
789 unfocus: (unfocusOptions) => {
790 const isFocused = this.focusedComponent === component;
791 const restoreState = this.overlayFocusRestore;
792 const hasPendingRestore = restoreState.status !== "inactive" && restoreState.overlay === entry;
793 if (!isFocused && !hasPendingRestore) return;
794 if (
795 restoreState.status === "blocked" &&
796 restoreState.overlay === entry &&
797 this.focusedComponent === restoreState.blockedBy
798 ) {
799 if (unfocusOptions) {
800 this.overlayFocusRestore = {
801 status: "blocked",
802 overlay: entry,
803 blockedBy: restoreState.blockedBy,
804 resume: { status: "focus-target", target: unfocusOptions.target },
805 };
806 } else {
807 this.clearOverlayFocusRestore();
808 }
809 this.requestRender();
810 return;
811 }
812 this.clearOverlayFocusRestoreFor(entry);
813 if (isFocused || unfocusOptions) {
814 const topVisible = this.getTopmostVisibleOverlay();
815 const fallbackTarget = topVisible && topVisible !== entry ? topVisible.component : entry.preFocus;
816 this.setFocus(unfocusOptions ? unfocusOptions.target : fallbackTarget);
817 }
818 this.requestRender();
819 },
820 isFocused: () => this.focusedComponent === component,
821 getBounds: () => {
822 if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry) || !entry.bounds) return undefined;
823 return { ...entry.bounds };
824 },
825 };
826 }
827
828 /** Hide the topmost overlay and restore previous focus. */
829 hideOverlay(): void {
830 const overlay = this.overlayStack[this.overlayStack.length - 1];
831 if (!overlay) return;
832 this.clearOverlayFocusRestoreFor(overlay);
833 this.retargetOverlayPreFocus(overlay);
834 this.overlayStack.pop();
835 if (this.focusedComponent === overlay.component) {
836 // Find topmost visible overlay, or fall back to preFocus
837 const topVisible = this.getTopmostVisibleOverlay();
838 this.setFocus(topVisible?.component ?? overlay.preFocus);
839 }
840 if (this.overlayStack.length === 0) this.hideTerminalCursor();
841 this.requestRender();
842 }
843
844 /** Hide the cursor while running. After stop(), the shell owns the cursor and it must stay visible. */
845 private hideTerminalCursor(): void {
846 if (!this.stopped) this.terminal.hideCursor();
847 }
848
849 /** Check if there are any visible overlays */
850 hasOverlay(): boolean {
851 return this.overlayStack.some((o) => this.isOverlayVisible(o));
852 }
853
854 /** Check if the focused component is a visible overlay */
855 protected isOverlayFocused(): boolean {
856 return this.overlayStack.some(
857 (entry) => entry.component === this.focusedComponent && this.isOverlayVisible(entry),
858 );
859 }
860
861 /** Keep overlay containers as keyboard focus owners when a nested control is clicked. */
862 protected resolveMouseFocusTarget(component: Component): Component {
863 for (let index = this.overlayStack.length - 1; index >= 0; index--) {
864 const overlay = this.overlayStack[index]!;
865 if (this.isOverlayVisible(overlay) && this.containsComponent(overlay.component, component)) {
866 return overlay.component;
867 }
868 }
869 return component;
870 }
871
872 /** Dispatch to the visually topmost overlay under the pointer. */
873 protected dispatchMouseToOverlay(event: TuiMouseEvent): { hit: boolean; result?: TuiMouseDispatchResult } {
874 for (let index = this.renderedOverlayLayouts.length - 1; index >= 0; index--) {
875 const layout = this.renderedOverlayLayouts[index]!;
876 if (
877 event.screenX < layout.col ||
878 event.screenX >= layout.col + layout.width ||
879 event.screenY < layout.row ||
880 event.screenY >= layout.row + layout.height
881 ) {
882 continue;
883 }
884 const result = dispatchMouseEvent(layout.entry.component, {
885 ...event,
886 x: event.screenX - layout.col,
887 y: event.screenY - layout.row,
888 width: layout.width,
889 height: layout.height,
890 });
891 return result
892 ? {
893 hit: true,
894 result: result.focus ? { ...result, focusTarget: layout.entry.component } : result,
895 }
896 : { hit: true };
897 }
898 return { hit: false };
899 }
900
901 /** Check if an overlay entry is currently visible */
902 private isOverlayVisible(entry: OverlayStackEntry): boolean {
903 if (entry.hidden) return false;
904 if (entry.options?.visible) {
905 return entry.options.visible(this.terminal.columns, this.terminal.rows);
906 }
907 return true;
908 }
909
910 /** Find the visual-frontmost visible capturing overlay, if any */
911 private getTopmostVisibleOverlay(): OverlayStackEntry | undefined {
912 let topmost: OverlayStackEntry | undefined;
913 for (const overlay of this.overlayStack) {
914 if (overlay.options?.nonCapturing || !this.isOverlayVisible(overlay)) continue;
915 if (!topmost || overlay.focusOrder > topmost.focusOrder) {
916 topmost = overlay;
917 }
918 }
919 return topmost;
920 }
921
922 override invalidate(): void {
923 for (const root of this.getMountedRoots()) root.invalidate();
924 for (const overlay of this.overlayStack) overlay.component.invalidate();
925 }
926
927 start(): void {
928 this.stopped = false;
929 this.beforeTerminalStart();
930 this.terminal.start(
931 (data) => this.handleTerminalInput(data),
932 () => this.requestRender(),
933 );
934 this.afterTerminalStart();
935 this.terminal.hideCursor();
936 if (this.terminalColorSchemeNotificationsEnabled) {
937 this.terminal.write("\x1b[?2031h");
938 }
939 this.queryCellSize();
940 this.requestRender();
941 }
942
943 addInputListener(listener: TuiInputListener): () => void {
944 this.inputListeners.add(listener);
945 return () => {
946 this.inputListeners.delete(listener);
947 };
948 }
949
950 removeInputListener(listener: TuiInputListener): void {
951 this.inputListeners.delete(listener);
952 }
953
954 onTerminalColorSchemeChange(listener: (scheme: TerminalColorScheme) => void): () => void {
955 this.terminalColorSchemeListeners.add(listener);
956 return () => {
957 this.terminalColorSchemeListeners.delete(listener);
958 };
959 }
960
961 setTerminalColorSchemeNotifications(enabled: boolean): void {
962 if (this.terminalColorSchemeNotificationsEnabled === enabled) {
963 return;
964 }
965 this.terminalColorSchemeNotificationsEnabled = enabled;
966 if (!this.stopped) {
967 this.terminal.write(enabled ? "\x1b[?2031h" : "\x1b[?2031l");
968 }
969 }
970
971 private queryCellSize(): void {
972 // Only query if terminal supports images (cell size is only used for image rendering)
973 if (!getCapabilities().images) {
974 return;
975 }
976 // Query terminal for cell size in pixels: CSI 16 t
977 // Response format: CSI 6 ; height ; width t
978 this.terminal.write("\x1b[16t");
979 }
980
981 stop(options: TuiStopOptions = {}): void {
982 this.stopped = true;
983 this.cancelRenderTimer();
984 if (this.terminalColorSchemeNotificationsEnabled) {
985 this.terminal.write("\x1b[?2031l");
986 }
987 this.beforeTerminalStop(options);
988 this.terminal.showCursor();
989 this.terminal.stop();
990 this.afterTerminalStop(options);
991 }
992
993 renderNow(force = false): void {
994 if (force) this.resetRenderState();
995 this.renderRequested = false;
996 this.cancelRenderTimer();
997 this.lastRenderAt = performance.now();
998 this.doRender();
999 }
1000
1001 requestRender(force = false): void {
1002 if (force) {
1003 this.resetRenderState();
1004 this.requestImmediateRender();
1005 return;
1006 }
1007 if (this.renderRequested) return;
1008 this.renderRequested = true;
1009 process.nextTick(() => this.scheduleRender());
1010 }
1011
1012 private requestImmediateRender(): void {
1013 this.cancelRenderTimer();
1014 this.renderRequested = true;
1015 if (this.immediateRenderScheduled) return;
1016 this.immediateRenderScheduled = true;
1017 process.nextTick(() => {
1018 this.immediateRenderScheduled = false;
1019 if (this.stopped || !this.renderRequested) return;
1020 // A previously queued scheduleRender() can create a timer before this
1021 // callback runs. User input must preempt that throttled frame.
1022 this.cancelRenderTimer();
1023 this.renderRequested = false;
1024 this.lastRenderAt = performance.now();
1025 this.doRender();
1026 });
1027 }
1028
1029 private cancelRenderTimer(): void {
1030 if (!this.renderTimer) return;
1031 clearTimeout(this.renderTimer);
1032 this.renderTimer = undefined;
1033 }
1034
1035 private scheduleRender(): void {
1036 if (this.stopped || this.renderTimer || !this.renderRequested) {
1037 return;
1038 }
1039 const elapsed = performance.now() - this.lastRenderAt;
1040 const delay = Math.max(0, TuiBase.MIN_RENDER_INTERVAL_MS - elapsed);
1041 this.renderTimer = setTimeout(() => {
1042 this.renderTimer = undefined;
1043 if (this.stopped || !this.renderRequested) {
1044 return;
1045 }
1046 this.renderRequested = false;
1047 this.lastRenderAt = performance.now();
1048 this.doRender();
1049 if (this.renderRequested) {
1050 this.scheduleRender();
1051 }
1052 }, delay);
1053 }
1054
1055 private handleTerminalInput(data: string): void {
1056 if (this.consumeTerminalColorResponse(data)) {
1057 return;
1058 }
1059 if (this.consumeTerminalColorSchemeReport(data)) {
1060 return;
1061 }
1062
1063 if (this.inputListeners.size > 0) {
1064 let current = data;
1065 for (const listener of this.inputListeners) {
1066 const result = listener(current);
1067 if (result?.consume) {
1068 return;
1069 }
1070 if (result?.data !== undefined) {
1071 current = result.data;
1072 }
1073 }
1074 if (current.length === 0) {
1075 return;
1076 }
1077 data = current;
1078 }
1079
1080 // Consume terminal cell size responses without blocking unrelated input.
1081 if (this.consumeCellSizeResponse(data)) {
1082 return;
1083 }
1084
1085 // Global debug key handler (Shift+Ctrl+D)
1086 if (matchesKey(data, "shift+ctrl+d") && this.onDebug) {
1087 this.onDebug();
1088 return;
1089 }
1090
1091 // If focused component is an overlay, verify it's still visible
1092 // (visibility can change due to terminal resize or visible() callback)
1093 const focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);
1094 if (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {
1095 // Focused overlay is no longer visible, redirect to topmost visible overlay
1096 const topVisible = this.getTopmostVisibleOverlay();
1097 if (topVisible) {
1098 this.setFocus(topVisible.component);
1099 } else {
1100 this.setFocusInternal({ component: focusedOverlay.preFocus, overlayFocusRestore: "preserve" });
1101 }
1102 }
1103
1104 const focusIsOverlay = this.overlayStack.some((o) => o.component === this.focusedComponent);
1105 if (!focusIsOverlay) {
1106 const restoreState = this.getVisibleOverlayFocusRestore();
1107 if (restoreState.status === "eligible") {
1108 this.setFocus(restoreState.overlay.component);
1109 } else if (restoreState.status === "blocked" && restoreState.blockedBy !== this.focusedComponent) {
1110 if (restoreState.resume.status === "restore-overlay") {
1111 this.setFocus(restoreState.overlay.component);
1112 } else {
1113 this.clearOverlayFocusRestore();
1114 this.setFocus(restoreState.resume.target);
1115 }
1116 }
1117 }
1118
1119 // Pass input to focused component (including Ctrl+C)
1120 // The focused component can decide how to handle Ctrl+C
1121 if (this.focusedComponent?.handleInput) {
1122 // Filter out key release events unless component opts in
1123 if (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {
1124 return;
1125 }
1126 this.focusedComponent.handleInput(data);
1127 // Keyboard input is latency-sensitive. Avoid the throttled timer path,
1128 // where even setTimeout(0) can take a full 16 ms tick on Windows.
1129 this.requestImmediateRender();
1130 }
1131 }
1132
1133 private consumeTerminalColorResponse(data: string): boolean {
1134 const query = this.pendingTerminalColorQueries[0];
1135 if (!query) {
1136 return false;
1137 }
1138 if (DEVICE_ATTRIBUTES_RESPONSE_PATTERN.test(data)) {
1139 this.pendingTerminalColorQueries.shift();
1140 this.completeTerminalColorQuery(query);
1141 return true;
1142 }
1143
1144 const response = parseOscColorResponse(data);
1145 if (!response) {
1146 return false;
1147 }
1148 const { target, rgb } = response;
1149 const key = String(target);
1150 if (!query.deliver || query.replied.has(key)) {
1151 return true;
1152 }
1153 query.replied.add(key);
1154 if (target === "foreground") {
1155 query.foreground = rgb;
1156 } else if (target === "background") {
1157 query.background = rgb;
1158 } else if (target < TERMINAL_PALETTE_SIZE) {
1159 query.palette[target] = rgb;
1160 }
1161 if (query.replied.size === TERMINAL_COLOR_REPLY_COUNT) {
1162 this.completeTerminalColorQuery(query);
1163 }
1164 return true;
1165 }
1166
1167 private terminalColorQueryResult(query: PendingTerminalColorQuery): TerminalColors {
1168 const palette = query.palette.every((color) => color !== undefined) ? (query.palette as RgbColor[]) : undefined;
1169 return { foreground: query.foreground, background: query.background, palette };
1170 }
1171
1172 private completeTerminalColorQuery(query: PendingTerminalColorQuery): void {
1173 const deliver = query.deliver;
1174 query.deliver = undefined;
1175 clearTimeout(query.timer);
1176 deliver?.(this.terminalColorQueryResult(query));
1177 }
1178
1179 private consumeTerminalColorSchemeReport(data: string): boolean {
1180 const scheme = parseTerminalColorSchemeReport(data);
1181 if (!scheme) {
1182 return false;
1183 }
1184
1185 for (const listener of this.terminalColorSchemeListeners) {
1186 listener(scheme);
1187 }
1188 return true;
1189 }
1190
1191 private consumeCellSizeResponse(data: string): boolean {
1192 // Response format: ESC [ 6 ; height ; width t
1193 const match = data.match(/^\x1b\[6;(\d+);(\d+)t$/);
1194 if (!match) {
1195 return false;
1196 }
1197
1198 const heightPx = parseInt(match[1], 10);
1199 const widthPx = parseInt(match[2], 10);
1200 if (heightPx <= 0 || widthPx <= 0) {
1201 return true;
1202 }
1203
1204 setCellDimensions({ widthPx, heightPx });
1205 // Invalidate all components so images re-render with correct dimensions.
1206 this.invalidate();
1207 this.requestRender();
1208 return true;
1209 }
1210
1211 /**
1212 * Resolve overlay layout from options.
1213 * Returns { width, row, col, maxHeight } for rendering.
1214 */
1215 private resolveOverlayLayout(
1216 options: OverlayOptions | undefined,
1217 overlayHeight: number,
1218 termWidth: number,
1219 termHeight: number,
1220 ): { width: number; row: number; col: number; maxHeight: number | undefined } {
1221 const opt = options ?? {};
1222
1223 // Parse margin (clamp to non-negative)
1224 const margin =
1225 typeof opt.margin === "number"
1226 ? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }
1227 : (opt.margin ?? {});
1228 const marginTop = Math.max(0, margin.top ?? 0);
1229 const marginRight = Math.max(0, margin.right ?? 0);
1230 const marginBottom = Math.max(0, margin.bottom ?? 0);
1231 const marginLeft = Math.max(0, margin.left ?? 0);
1232
1233 // Available space after margins
1234 const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
1235 const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
1236
1237 // === Resolve width ===
1238 let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
1239 // Apply minWidth
1240 if (opt.minWidth !== undefined) {
1241 width = Math.max(width, opt.minWidth);
1242 }
1243 // Clamp to available space
1244 width = Math.max(1, Math.min(width, availWidth));
1245
1246 // === Resolve maxHeight ===
1247 let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
1248 // Clamp to available space
1249 if (maxHeight !== undefined) {
1250 maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
1251 }
1252
1253 // Effective overlay height (may be clamped by maxHeight)
1254 const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
1255
1256 // === Resolve position ===
1257 let row: number;
1258 let col: number;
1259
1260 if (opt.row !== undefined) {
1261 if (typeof opt.row === "string") {
1262 // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
1263 const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
1264 if (match) {
1265 const maxRow = Math.max(0, availHeight - effectiveHeight);
1266 const percent = parseFloat(match[1]) / 100;
1267 row = marginTop + Math.floor(maxRow * percent);
1268 } else {
1269 // Invalid format, fall back to center
1270 row = this.resolveAnchorRow("center", effectiveHeight, availHeight, marginTop);
1271 }
1272 } else {
1273 // Absolute row position
1274 row = opt.row;
1275 }
1276 } else {
1277 // Anchor-based (default: center)
1278 const anchor = opt.anchor ?? "center";
1279 row = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
1280 }
1281
1282 if (opt.col !== undefined) {
1283 if (typeof opt.col === "string") {
1284 // Percentage: 0% = left, 100% = right (overlay stays within bounds)
1285 const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
1286 if (match) {
1287 const maxCol = Math.max(0, availWidth - width);
1288 const percent = parseFloat(match[1]) / 100;
1289 col = marginLeft + Math.floor(maxCol * percent);
1290 } else {
1291 // Invalid format, fall back to center
1292 col = this.resolveAnchorCol("center", width, availWidth, marginLeft);
1293 }
1294 } else {
1295 // Absolute column position
1296 col = opt.col;
1297 }
1298 } else {
1299 // Anchor-based (default: center)
1300 const anchor = opt.anchor ?? "center";
1301 col = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);
1302 }
1303
1304 // Apply offsets
1305 if (opt.offsetY !== undefined) row += opt.offsetY;
1306 if (opt.offsetX !== undefined) col += opt.offsetX;
1307
1308 // Clamp to terminal bounds (respecting margins)
1309 row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
1310 col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
1311
1312 return { width, row, col, maxHeight };
1313 }
1314
1315 private resolveAnchorRow(anchor: OverlayAnchor, height: number, availHeight: number, marginTop: number): number {
1316 switch (anchor) {
1317 case "top-left":
1318 case "top-center":
1319 case "top-right":
1320 return marginTop;
1321 case "bottom-left":
1322 case "bottom-center":
1323 case "bottom-right":
1324 return marginTop + availHeight - height;
1325 case "left-center":
1326 case "center":
1327 case "right-center":
1328 return marginTop + Math.floor((availHeight - height) / 2);
1329 }
1330 }
1331
1332 private resolveAnchorCol(anchor: OverlayAnchor, width: number, availWidth: number, marginLeft: number): number {
1333 switch (anchor) {
1334 case "top-left":
1335 case "left-center":
1336 case "bottom-left":
1337 return marginLeft;
1338 case "top-right":
1339 case "right-center":
1340 case "bottom-right":
1341 return marginLeft + availWidth - width;
1342 case "top-center":
1343 case "center":
1344 case "bottom-center":
1345 return marginLeft + Math.floor((availWidth - width) / 2);
1346 }
1347 }
1348
1349 /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
1350 protected compositeOverlays(lines: string[], termWidth: number, termHeight: number): string[] {
1351 if (this.overlayStack.length === 0) {
1352 this.renderedOverlayLayouts = [];
1353 return lines;
1354 }
1355 const result = [...lines];
1356
1357 for (const entry of this.overlayStack) entry.bounds = undefined;
1358
1359 // Pre-render all visible overlays and calculate positions
1360 const rendered: { entry: OverlayStackEntry; overlayLines: string[]; row: number; col: number; w: number }[] = [];
1361 let minLinesNeeded = result.length;
1362
1363 const visibleEntries = this.overlayStack.filter((e) => this.isOverlayVisible(e));
1364 visibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);
1365 for (const entry of visibleEntries) {
1366 const { component, options } = entry;
1367
1368 // Get layout with height=0 first to determine width and maxHeight
1369 // (width and maxHeight don't depend on overlay height)
1370 const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
1371
1372 // Render component at calculated width
1373 let overlayLines = this.resolveFakeCursors(component.render(width));
1374
1375 // Apply maxHeight if specified
1376 if (maxHeight !== undefined && overlayLines.length > maxHeight) {
1377 overlayLines = overlayLines.slice(0, maxHeight);
1378 }
1379
1380 // Get final row/col with actual overlay height
1381 const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
1382 entry.bounds = { row, col, width, height: overlayLines.length };
1383
1384 rendered.push({ entry, overlayLines, row, col, w: width });
1385 minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
1386 }
1387 this.renderedOverlayLayouts = rendered.map(({ entry, row, col, w, overlayLines }) => ({
1388 entry,
1389 row,
1390 col,
1391 width: w,
1392 height: overlayLines.length,
1393 }));
1394
1395 // Pad to at least terminal height so overlays have screen-relative positions.
1396 // Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing
1397 // inflation that pushed content into scrollback on terminal widen.
1398 const workingHeight = Math.max(result.length, termHeight, minLinesNeeded);
1399
1400 // Extend result with empty lines if content is too short for overlay placement or working area
1401 while (result.length < workingHeight) {
1402 result.push("");
1403 }
1404
1405 const viewportStart = Math.max(0, workingHeight - termHeight);
1406
1407 // Composite each overlay
1408 for (const { overlayLines, row, col, w } of rendered) {
1409 for (let i = 0; i < overlayLines.length; i++) {
1410 const idx = viewportStart + row + i;
1411 if (idx >= 0 && idx < result.length) {
1412 // Defensive: truncate overlay line to declared width before compositing
1413 // (components should already respect width, but this ensures it)
1414 const truncatedOverlayLine =
1415 visibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];
1416 result[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
1417 }
1418 }
1419 }
1420
1421 return result;
1422 }
1423
1424 protected applyLineResets(lines: string[]): string[] {
1425 const reset = SEGMENT_RESET;
1426 for (let i = 0; i < lines.length; i++) {
1427 const line = lines[i];
1428 if (!isImageLine(line)) {
1429 lines[i] = normalizeTerminalOutput(line) + reset;
1430 }
1431 }
1432 return lines;
1433 }
1434
1435 private compositeLineAt(
1436 baseLine: string,
1437 overlayLine: string,
1438 startCol: number,
1439 overlayWidth: number,
1440 totalWidth: number,
1441 ): string {
1442 return compositeTuiLine(baseLine, overlayLine, startCol, overlayWidth, totalWidth);
1443 }
1444
1445 /**
1446 * Find and extract cursor position from rendered lines.
1447 * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
1448 * Only scans the bottom terminal height lines (visible viewport).
1449 * @param lines - Rendered lines to search
1450 * @param height - Terminal height (visible viewport size)
1451 * @returns Cursor position { row, col } or null if no marker found
1452 */
1453 protected extractCursorPosition(lines: string[], height: number): { row: number; col: number } | null {
1454 // Only scan the bottom `height` lines (visible viewport)
1455 const viewportTop = Math.max(0, lines.length - height);
1456 for (let row = lines.length - 1; row >= viewportTop; row--) {
1457 const line = lines[row];
1458 const markerIndex = line.indexOf(CURSOR_MARKER);
1459 if (markerIndex !== -1) {
1460 // Calculate visual column (width of text before marker)
1461 const beforeMarker = line.slice(0, markerIndex);
1462 const col = visibleWidth(beforeMarker);
1463
1464 // Strip marker from the line
1465 lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
1466
1467 return { row, col };
1468 }
1469 }
1470 return null;
1471 }
1472
1473 /**
1474 * Resolve fake cursor markers to reverse video. When the hardware cursor is shown, a fake cursor
1475 * directly after CURSOR_MARKER is dropped because the terminal cursor is drawn there. Fake cursors
1476 * of components without focus have no CURSOR_MARKER and stay visible.
1477 */
1478 protected resolveFakeCursors(lines: string[]): string[] {
1479 return lines.map((line) => {
1480 if (!line.includes(FAKE_CURSOR_START)) return line;
1481 const resolved = this.showHardwareCursor ? line.replace(FOCUSED_FAKE_CURSOR, "$1$2") : line;
1482 return resolved.replaceAll(FAKE_CURSOR_START, "\x1b[7m").replaceAll(FAKE_CURSOR_END, "\x1b[27m");
1483 });
1484 }
1485
1486 /**
1487 * Query the terminal's theme colors: the default foreground (OSC 10), the default background
1488 * (OSC 11), and ANSI colors 0-15 (OSC 4), followed by a DA1 request that marks the end of the
1489 * replies. Resolves when the DA1 reply or all color replies arrive, or when the timeout expires.
1490 * Colors the terminal did not report are undefined; the palette is only set when all 16 arrived.
1491 * @param timeoutMs Query timeout in milliseconds, for terminals that do not answer DA1 either.
1492 * @param onLateReply Receives the replies if the query completes after the timeout, e.g. over slow links.
1493 */
1494 queryTerminalColors({
1495 timeoutMs,
1496 onLateReply,
1497 }: {
1498 timeoutMs: number;
1499 onLateReply?: (colors: TerminalColors) => void;
1500 }): Promise<TerminalColors> {
1501 return new Promise((resolve) => {
1502 const query: PendingTerminalColorQuery = {
1503 palette: Array.from({ length: TERMINAL_PALETTE_SIZE }, () => undefined),
1504 replied: new Set(),
1505 deliver: resolve,
1506 timer: undefined,
1507 };
1508 // Resolve with the replies so far, and keep collecting late replies for `onLateReply`.
1509 query.timer = setTimeout(() => {
1510 query.deliver = onLateReply;
1511 resolve(this.terminalColorQueryResult(query));
1512 }, timeoutMs);
1513 this.pendingTerminalColorQueries.push(query);
1514 this.terminal.write(TERMINAL_COLOR_QUERY);
1515 });
1516 }
1517}