@draht/tui 2026.3.2-2
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 +761 -0
- package/dist/autocomplete.d.ts +50 -0
- package/dist/autocomplete.d.ts.map +1 -0
- package/dist/autocomplete.js +596 -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 +205 -0
- package/dist/components/editor.d.ts.map +1 -0
- package/dist/components/editor.js +1679 -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 +69 -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 +433 -0
- package/dist/components/input.js.map +1 -0
- package/dist/components/loader.d.ts +21 -0
- package/dist/components/loader.d.ts.map +1 -0
- package/dist/components/loader.js +49 -0
- package/dist/components/loader.js.map +1 -0
- package/dist/components/markdown.d.ts +95 -0
- package/dist/components/markdown.d.ts.map +1 -0
- package/dist/components/markdown.js +629 -0
- package/dist/components/markdown.js.map +1 -0
- package/dist/components/select-list.d.ts +32 -0
- package/dist/components/select-list.d.ts.map +1 -0
- package/dist/components/select-list.js +152 -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 +185 -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 +107 -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 +39 -0
- package/dist/keybindings.d.ts.map +1 -0
- package/dist/keybindings.js +114 -0
- package/dist/keybindings.js.map +1 -0
- package/dist/keys.d.ts +160 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/keys.js +959 -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/stdin-buffer.d.ts +48 -0
- package/dist/stdin-buffer.d.ts.map +1 -0
- package/dist/stdin-buffer.js +317 -0
- package/dist/stdin-buffer.js.map +1 -0
- package/dist/terminal-image.d.ts +68 -0
- package/dist/terminal-image.d.ts.map +1 -0
- package/dist/terminal-image.js +288 -0
- package/dist/terminal-image.js.map +1 -0
- package/dist/terminal.d.ts +78 -0
- package/dist/terminal.d.ts.map +1 -0
- package/dist/terminal.js +249 -0
- package/dist/terminal.js.map +1 -0
- package/dist/tui.d.ts +210 -0
- package/dist/tui.d.ts.map +1 -0
- package/dist/tui.js +955 -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 +78 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +800 -0
- package/dist/utils.js.map +1 -0
- package/package.json +53 -0
package/dist/terminal.js
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { setKittyProtocolActive } from "./keys.js";
|
|
4
|
+
import { StdinBuffer } from "./stdin-buffer.js";
|
|
5
|
+
const cjsRequire = createRequire(import.meta.url);
|
|
6
|
+
/**
|
|
7
|
+
* Real terminal using process.stdin/stdout
|
|
8
|
+
*/
|
|
9
|
+
export class ProcessTerminal {
|
|
10
|
+
wasRaw = false;
|
|
11
|
+
inputHandler;
|
|
12
|
+
resizeHandler;
|
|
13
|
+
_kittyProtocolActive = false;
|
|
14
|
+
stdinBuffer;
|
|
15
|
+
stdinDataHandler;
|
|
16
|
+
writeLogPath = process.env.PI_TUI_WRITE_LOG || "";
|
|
17
|
+
get kittyProtocolActive() {
|
|
18
|
+
return this._kittyProtocolActive;
|
|
19
|
+
}
|
|
20
|
+
start(onInput, onResize) {
|
|
21
|
+
this.inputHandler = onInput;
|
|
22
|
+
this.resizeHandler = onResize;
|
|
23
|
+
// Save previous state and enable raw mode
|
|
24
|
+
this.wasRaw = process.stdin.isRaw || false;
|
|
25
|
+
if (process.stdin.setRawMode) {
|
|
26
|
+
process.stdin.setRawMode(true);
|
|
27
|
+
}
|
|
28
|
+
process.stdin.setEncoding("utf8");
|
|
29
|
+
process.stdin.resume();
|
|
30
|
+
// Enable bracketed paste mode - terminal will wrap pastes in \x1b[200~ ... \x1b[201~
|
|
31
|
+
process.stdout.write("\x1b[?2004h");
|
|
32
|
+
// Set up resize handler immediately
|
|
33
|
+
process.stdout.on("resize", this.resizeHandler);
|
|
34
|
+
// Refresh terminal dimensions - they may be stale after suspend/resume
|
|
35
|
+
// (SIGWINCH is lost while process is stopped). Unix only.
|
|
36
|
+
if (process.platform !== "win32") {
|
|
37
|
+
process.kill(process.pid, "SIGWINCH");
|
|
38
|
+
}
|
|
39
|
+
// On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends
|
|
40
|
+
// VT escape sequences (e.g. \x1b[Z for Shift+Tab) instead of raw console
|
|
41
|
+
// events that lose modifier information. Must run AFTER setRawMode(true)
|
|
42
|
+
// since that resets console mode flags.
|
|
43
|
+
this.enableWindowsVTInput();
|
|
44
|
+
// Query and enable Kitty keyboard protocol
|
|
45
|
+
// The query handler intercepts input temporarily, then installs the user's handler
|
|
46
|
+
// See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
|
|
47
|
+
this.queryAndEnableKittyProtocol();
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Set up StdinBuffer to split batched input into individual sequences.
|
|
51
|
+
* This ensures components receive single events, making matchesKey/isKeyRelease work correctly.
|
|
52
|
+
*
|
|
53
|
+
* Also watches for Kitty protocol response and enables it when detected.
|
|
54
|
+
* This is done here (after stdinBuffer parsing) rather than on raw stdin
|
|
55
|
+
* to handle the case where the response arrives split across multiple events.
|
|
56
|
+
*/
|
|
57
|
+
setupStdinBuffer() {
|
|
58
|
+
this.stdinBuffer = new StdinBuffer({ timeout: 10 });
|
|
59
|
+
// Kitty protocol response pattern: \x1b[?<flags>u
|
|
60
|
+
const kittyResponsePattern = /^\x1b\[\?(\d+)u$/;
|
|
61
|
+
// Forward individual sequences to the input handler
|
|
62
|
+
this.stdinBuffer.on("data", (sequence) => {
|
|
63
|
+
// Check for Kitty protocol response (only if not already enabled)
|
|
64
|
+
if (!this._kittyProtocolActive) {
|
|
65
|
+
const match = sequence.match(kittyResponsePattern);
|
|
66
|
+
if (match) {
|
|
67
|
+
this._kittyProtocolActive = true;
|
|
68
|
+
setKittyProtocolActive(true);
|
|
69
|
+
// Enable Kitty keyboard protocol (push flags)
|
|
70
|
+
// Flag 1 = disambiguate escape codes
|
|
71
|
+
// Flag 2 = report event types (press/repeat/release)
|
|
72
|
+
// Flag 4 = report alternate keys (shifted key, base layout key)
|
|
73
|
+
// Base layout key enables shortcuts to work with non-Latin keyboard layouts
|
|
74
|
+
process.stdout.write("\x1b[>7u");
|
|
75
|
+
return; // Don't forward protocol response to TUI
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (this.inputHandler) {
|
|
79
|
+
this.inputHandler(sequence);
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
// Re-wrap paste content with bracketed paste markers for existing editor handling
|
|
83
|
+
this.stdinBuffer.on("paste", (content) => {
|
|
84
|
+
if (this.inputHandler) {
|
|
85
|
+
this.inputHandler(`\x1b[200~${content}\x1b[201~`);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
// Handler that pipes stdin data through the buffer
|
|
89
|
+
this.stdinDataHandler = (data) => {
|
|
90
|
+
this.stdinBuffer.process(data);
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Query terminal for Kitty keyboard protocol support and enable if available.
|
|
95
|
+
*
|
|
96
|
+
* Sends CSI ? u to query current flags. If terminal responds with CSI ? <flags> u,
|
|
97
|
+
* it supports the protocol and we enable it with CSI > 1 u.
|
|
98
|
+
*
|
|
99
|
+
* The response is detected in setupStdinBuffer's data handler, which properly
|
|
100
|
+
* handles the case where the response arrives split across multiple stdin events.
|
|
101
|
+
*/
|
|
102
|
+
queryAndEnableKittyProtocol() {
|
|
103
|
+
this.setupStdinBuffer();
|
|
104
|
+
process.stdin.on("data", this.stdinDataHandler);
|
|
105
|
+
process.stdout.write("\x1b[?u");
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin
|
|
109
|
+
* console handle so the terminal sends VT sequences for modified keys
|
|
110
|
+
* (e.g. \x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW
|
|
111
|
+
* discards modifier state and Shift+Tab arrives as plain \t.
|
|
112
|
+
*/
|
|
113
|
+
enableWindowsVTInput() {
|
|
114
|
+
if (process.platform !== "win32")
|
|
115
|
+
return;
|
|
116
|
+
try {
|
|
117
|
+
// Dynamic require to avoid bundling koffi's 74MB of cross-platform
|
|
118
|
+
// native binaries into every compiled binary. Koffi is only needed
|
|
119
|
+
// on Windows for VT input support.
|
|
120
|
+
const koffi = cjsRequire("koffi");
|
|
121
|
+
const k32 = koffi.load("kernel32.dll");
|
|
122
|
+
const GetStdHandle = k32.func("void* __stdcall GetStdHandle(int)");
|
|
123
|
+
const GetConsoleMode = k32.func("bool __stdcall GetConsoleMode(void*, _Out_ uint32_t*)");
|
|
124
|
+
const SetConsoleMode = k32.func("bool __stdcall SetConsoleMode(void*, uint32_t)");
|
|
125
|
+
const STD_INPUT_HANDLE = -10;
|
|
126
|
+
const ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;
|
|
127
|
+
const handle = GetStdHandle(STD_INPUT_HANDLE);
|
|
128
|
+
const mode = new Uint32Array(1);
|
|
129
|
+
GetConsoleMode(handle, mode);
|
|
130
|
+
SetConsoleMode(handle, mode[0] | ENABLE_VIRTUAL_TERMINAL_INPUT);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// koffi not available — Shift+Tab won't be distinguishable from Tab
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async drainInput(maxMs = 1000, idleMs = 50) {
|
|
137
|
+
if (this._kittyProtocolActive) {
|
|
138
|
+
// Disable Kitty keyboard protocol first so any late key releases
|
|
139
|
+
// do not generate new Kitty escape sequences.
|
|
140
|
+
process.stdout.write("\x1b[<u");
|
|
141
|
+
this._kittyProtocolActive = false;
|
|
142
|
+
setKittyProtocolActive(false);
|
|
143
|
+
}
|
|
144
|
+
const previousHandler = this.inputHandler;
|
|
145
|
+
this.inputHandler = undefined;
|
|
146
|
+
let lastDataTime = Date.now();
|
|
147
|
+
const onData = () => {
|
|
148
|
+
lastDataTime = Date.now();
|
|
149
|
+
};
|
|
150
|
+
process.stdin.on("data", onData);
|
|
151
|
+
const endTime = Date.now() + maxMs;
|
|
152
|
+
try {
|
|
153
|
+
while (true) {
|
|
154
|
+
const now = Date.now();
|
|
155
|
+
const timeLeft = endTime - now;
|
|
156
|
+
if (timeLeft <= 0)
|
|
157
|
+
break;
|
|
158
|
+
if (now - lastDataTime >= idleMs)
|
|
159
|
+
break;
|
|
160
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
process.stdin.removeListener("data", onData);
|
|
165
|
+
this.inputHandler = previousHandler;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
stop() {
|
|
169
|
+
// Disable bracketed paste mode
|
|
170
|
+
process.stdout.write("\x1b[?2004l");
|
|
171
|
+
// Disable Kitty keyboard protocol if not already done by drainInput()
|
|
172
|
+
if (this._kittyProtocolActive) {
|
|
173
|
+
process.stdout.write("\x1b[<u");
|
|
174
|
+
this._kittyProtocolActive = false;
|
|
175
|
+
setKittyProtocolActive(false);
|
|
176
|
+
}
|
|
177
|
+
// Clean up StdinBuffer
|
|
178
|
+
if (this.stdinBuffer) {
|
|
179
|
+
this.stdinBuffer.destroy();
|
|
180
|
+
this.stdinBuffer = undefined;
|
|
181
|
+
}
|
|
182
|
+
// Remove event handlers
|
|
183
|
+
if (this.stdinDataHandler) {
|
|
184
|
+
process.stdin.removeListener("data", this.stdinDataHandler);
|
|
185
|
+
this.stdinDataHandler = undefined;
|
|
186
|
+
}
|
|
187
|
+
this.inputHandler = undefined;
|
|
188
|
+
if (this.resizeHandler) {
|
|
189
|
+
process.stdout.removeListener("resize", this.resizeHandler);
|
|
190
|
+
this.resizeHandler = undefined;
|
|
191
|
+
}
|
|
192
|
+
// Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being
|
|
193
|
+
// re-interpreted after raw mode is disabled. This fixes a race condition
|
|
194
|
+
// where Ctrl+D could close the parent shell over SSH.
|
|
195
|
+
process.stdin.pause();
|
|
196
|
+
// Restore raw mode state
|
|
197
|
+
if (process.stdin.setRawMode) {
|
|
198
|
+
process.stdin.setRawMode(this.wasRaw);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
write(data) {
|
|
202
|
+
process.stdout.write(data);
|
|
203
|
+
if (this.writeLogPath) {
|
|
204
|
+
try {
|
|
205
|
+
fs.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
// Ignore logging errors
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
get columns() {
|
|
213
|
+
return process.stdout.columns || 80;
|
|
214
|
+
}
|
|
215
|
+
get rows() {
|
|
216
|
+
return process.stdout.rows || 24;
|
|
217
|
+
}
|
|
218
|
+
moveBy(lines) {
|
|
219
|
+
if (lines > 0) {
|
|
220
|
+
// Move down
|
|
221
|
+
process.stdout.write(`\x1b[${lines}B`);
|
|
222
|
+
}
|
|
223
|
+
else if (lines < 0) {
|
|
224
|
+
// Move up
|
|
225
|
+
process.stdout.write(`\x1b[${-lines}A`);
|
|
226
|
+
}
|
|
227
|
+
// lines === 0: no movement
|
|
228
|
+
}
|
|
229
|
+
hideCursor() {
|
|
230
|
+
process.stdout.write("\x1b[?25l");
|
|
231
|
+
}
|
|
232
|
+
showCursor() {
|
|
233
|
+
process.stdout.write("\x1b[?25h");
|
|
234
|
+
}
|
|
235
|
+
clearLine() {
|
|
236
|
+
process.stdout.write("\x1b[K");
|
|
237
|
+
}
|
|
238
|
+
clearFromCursor() {
|
|
239
|
+
process.stdout.write("\x1b[J");
|
|
240
|
+
}
|
|
241
|
+
clearScreen() {
|
|
242
|
+
process.stdout.write("\x1b[2J\x1b[H"); // Clear screen and move to home (1,1)
|
|
243
|
+
}
|
|
244
|
+
setTitle(title) {
|
|
245
|
+
// OSC 0;title BEL - set terminal window title
|
|
246
|
+
process.stdout.write(`\x1b]0;${title}\x07`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
//# sourceMappingURL=terminal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"terminal.js","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,MAAM,UAAU,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AA8ClD;;GAEG;AACH,MAAM,OAAO,eAAe;IACnB,MAAM,GAAG,KAAK,CAAC;IACf,YAAY,CAA0B;IACtC,aAAa,CAAc;IAC3B,oBAAoB,GAAG,KAAK,CAAC;IAC7B,WAAW,CAAe;IAC1B,gBAAgB,CAA0B;IAC1C,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,gBAAgB,IAAI,EAAE,CAAC;IAE1D,IAAI,mBAAmB,GAAY;QAClC,OAAO,IAAI,CAAC,oBAAoB,CAAC;IAAA,CACjC;IAED,KAAK,CAAC,OAA+B,EAAE,QAAoB,EAAQ;QAClE,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC;QAC5B,IAAI,CAAC,aAAa,GAAG,QAAQ,CAAC;QAE9B,0CAA0C;QAC1C,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC;QAC3C,IAAI,OAAO,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC;YAC9B,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QAChC,CAAC;QACD,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QACl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YACV,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,CAAC;QACzC,CAAC;QACD,2BAA2B;IAD1B,CAED;IAED,UAAU,GAAS;QAClB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAAA,CAClC;IAED,UAAU,GAAS;QAClB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAAA,CAClC;IAED,SAAS,GAAS;QACjB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAAA,CAC/B;IAED,eAAe,GAAS;QACvB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAAA,CAC/B;IAED,WAAW,GAAS;QACnB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC,sCAAsC;IAAvC,CACtC;IAED,QAAQ,CAAC,KAAa,EAAQ;QAC7B,8CAA8C;QAC9C,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,KAAK,MAAM,CAAC,CAAC;IAAA,CAC5C;CACD","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { setKittyProtocolActive } from \"./keys.js\";\nimport { StdinBuffer } from \"./stdin-buffer.js\";\n\nconst cjsRequire = createRequire(import.meta.url);\n\n/**\n * Minimal terminal interface for TUI\n */\nexport interface Terminal {\n\t// Start the terminal with input and resize handlers\n\tstart(onInput: (data: string) => void, onResize: () => void): void;\n\n\t// Stop the terminal and restore state\n\tstop(): void;\n\n\t/**\n\t * Drain stdin before exiting to prevent Kitty key release events from\n\t * leaking to the parent shell over slow SSH connections.\n\t * @param maxMs - Maximum time to drain (default: 1000ms)\n\t * @param idleMs - Exit early if no input arrives within this time (default: 50ms)\n\t */\n\tdrainInput(maxMs?: number, idleMs?: number): Promise<void>;\n\n\t// Write output to terminal\n\twrite(data: string): void;\n\n\t// Get terminal dimensions\n\tget columns(): number;\n\tget rows(): number;\n\n\t// Whether Kitty keyboard protocol is active\n\tget kittyProtocolActive(): boolean;\n\n\t// Cursor positioning (relative to current position)\n\tmoveBy(lines: number): void; // Move cursor up (negative) or down (positive) by N lines\n\n\t// Cursor visibility\n\thideCursor(): void; // Hide the cursor\n\tshowCursor(): void; // Show the cursor\n\n\t// Clear operations\n\tclearLine(): void; // Clear current line\n\tclearFromCursor(): void; // Clear from cursor to end of screen\n\tclearScreen(): void; // Clear entire screen and move cursor to (0,0)\n\n\t// Title operations\n\tsetTitle(title: string): void; // Set terminal window title\n}\n\n/**\n * Real terminal using process.stdin/stdout\n */\nexport class ProcessTerminal implements Terminal {\n\tprivate wasRaw = false;\n\tprivate inputHandler?: (data: string) => void;\n\tprivate resizeHandler?: () => void;\n\tprivate _kittyProtocolActive = false;\n\tprivate stdinBuffer?: StdinBuffer;\n\tprivate stdinDataHandler?: (data: string) => void;\n\tprivate writeLogPath = process.env.PI_TUI_WRITE_LOG || \"\";\n\n\tget kittyProtocolActive(): boolean {\n\t\treturn this._kittyProtocolActive;\n\t}\n\n\tstart(onInput: (data: string) => void, onResize: () => void): void {\n\t\tthis.inputHandler = onInput;\n\t\tthis.resizeHandler = onResize;\n\n\t\t// Save previous state and enable raw mode\n\t\tthis.wasRaw = process.stdin.isRaw || false;\n\t\tif (process.stdin.setRawMode) {\n\t\t\tprocess.stdin.setRawMode(true);\n\t\t}\n\t\tprocess.stdin.setEncoding(\"utf8\");\n\t\tprocess.stdin.resume();\n\n\t\t// Enable bracketed paste mode - terminal will wrap pastes in \\x1b[200~ ... \\x1b[201~\n\t\tprocess.stdout.write(\"\\x1b[?2004h\");\n\n\t\t// Set up resize handler immediately\n\t\tprocess.stdout.on(\"resize\", this.resizeHandler);\n\n\t\t// Refresh terminal dimensions - they may be stale after suspend/resume\n\t\t// (SIGWINCH is lost while process is stopped). Unix only.\n\t\tif (process.platform !== \"win32\") {\n\t\t\tprocess.kill(process.pid, \"SIGWINCH\");\n\t\t}\n\n\t\t// On Windows, enable ENABLE_VIRTUAL_TERMINAL_INPUT so the console sends\n\t\t// VT escape sequences (e.g. \\x1b[Z for Shift+Tab) instead of raw console\n\t\t// events that lose modifier information. Must run AFTER setRawMode(true)\n\t\t// since that resets console mode flags.\n\t\tthis.enableWindowsVTInput();\n\n\t\t// Query and enable Kitty keyboard protocol\n\t\t// The query handler intercepts input temporarily, then installs the user's handler\n\t\t// See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/\n\t\tthis.queryAndEnableKittyProtocol();\n\t}\n\n\t/**\n\t * Set up StdinBuffer to split batched input into individual sequences.\n\t * This ensures components receive single events, making matchesKey/isKeyRelease work correctly.\n\t *\n\t * Also watches for Kitty protocol response and enables it when detected.\n\t * This is done here (after stdinBuffer parsing) rather than on raw stdin\n\t * to handle the case where the response arrives split across multiple events.\n\t */\n\tprivate setupStdinBuffer(): void {\n\t\tthis.stdinBuffer = new StdinBuffer({ timeout: 10 });\n\n\t\t// Kitty protocol response pattern: \\x1b[?<flags>u\n\t\tconst kittyResponsePattern = /^\\x1b\\[\\?(\\d+)u$/;\n\n\t\t// Forward individual sequences to the input handler\n\t\tthis.stdinBuffer.on(\"data\", (sequence) => {\n\t\t\t// Check for Kitty protocol response (only if not already enabled)\n\t\t\tif (!this._kittyProtocolActive) {\n\t\t\t\tconst match = sequence.match(kittyResponsePattern);\n\t\t\t\tif (match) {\n\t\t\t\t\tthis._kittyProtocolActive = true;\n\t\t\t\t\tsetKittyProtocolActive(true);\n\n\t\t\t\t\t// Enable Kitty keyboard protocol (push flags)\n\t\t\t\t\t// Flag 1 = disambiguate escape codes\n\t\t\t\t\t// Flag 2 = report event types (press/repeat/release)\n\t\t\t\t\t// Flag 4 = report alternate keys (shifted key, base layout key)\n\t\t\t\t\t// Base layout key enables shortcuts to work with non-Latin keyboard layouts\n\t\t\t\t\tprocess.stdout.write(\"\\x1b[>7u\");\n\t\t\t\t\treturn; // Don't forward protocol response to TUI\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(sequence);\n\t\t\t}\n\t\t});\n\n\t\t// Re-wrap paste content with bracketed paste markers for existing editor handling\n\t\tthis.stdinBuffer.on(\"paste\", (content) => {\n\t\t\tif (this.inputHandler) {\n\t\t\t\tthis.inputHandler(`\\x1b[200~${content}\\x1b[201~`);\n\t\t\t}\n\t\t});\n\n\t\t// Handler that pipes stdin data through the buffer\n\t\tthis.stdinDataHandler = (data: string) => {\n\t\t\tthis.stdinBuffer!.process(data);\n\t\t};\n\t}\n\n\t/**\n\t * Query terminal for Kitty keyboard protocol support and enable if available.\n\t *\n\t * Sends CSI ? u to query current flags. If terminal responds with CSI ? <flags> u,\n\t * it supports the protocol and we enable it with CSI > 1 u.\n\t *\n\t * The response is detected in setupStdinBuffer's data handler, which properly\n\t * handles the case where the response arrives split across multiple stdin events.\n\t */\n\tprivate queryAndEnableKittyProtocol(): void {\n\t\tthis.setupStdinBuffer();\n\t\tprocess.stdin.on(\"data\", this.stdinDataHandler!);\n\t\tprocess.stdout.write(\"\\x1b[?u\");\n\t}\n\n\t/**\n\t * On Windows, add ENABLE_VIRTUAL_TERMINAL_INPUT (0x0200) to the stdin\n\t * console handle so the terminal sends VT sequences for modified keys\n\t * (e.g. \\x1b[Z for Shift+Tab). Without this, libuv's ReadConsoleInputW\n\t * discards modifier state and Shift+Tab arrives as plain \\t.\n\t */\n\tprivate enableWindowsVTInput(): void {\n\t\tif (process.platform !== \"win32\") return;\n\t\ttry {\n\t\t\t// Dynamic require to avoid bundling koffi's 74MB of cross-platform\n\t\t\t// native binaries into every compiled binary. Koffi is only needed\n\t\t\t// on Windows for VT input support.\n\t\t\tconst koffi = cjsRequire(\"koffi\");\n\t\t\tconst k32 = koffi.load(\"kernel32.dll\");\n\t\t\tconst GetStdHandle = k32.func(\"void* __stdcall GetStdHandle(int)\");\n\t\t\tconst GetConsoleMode = k32.func(\"bool __stdcall GetConsoleMode(void*, _Out_ uint32_t*)\");\n\t\t\tconst SetConsoleMode = k32.func(\"bool __stdcall SetConsoleMode(void*, uint32_t)\");\n\n\t\t\tconst STD_INPUT_HANDLE = -10;\n\t\t\tconst ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;\n\t\t\tconst handle = GetStdHandle(STD_INPUT_HANDLE);\n\t\t\tconst mode = new Uint32Array(1);\n\t\t\tGetConsoleMode(handle, mode);\n\t\t\tSetConsoleMode(handle, mode[0]! | ENABLE_VIRTUAL_TERMINAL_INPUT);\n\t\t} catch {\n\t\t\t// koffi not available — Shift+Tab won't be distinguishable from Tab\n\t\t}\n\t}\n\n\tasync drainInput(maxMs = 1000, idleMs = 50): Promise<void> {\n\t\tif (this._kittyProtocolActive) {\n\t\t\t// Disable Kitty keyboard protocol first so any late key releases\n\t\t\t// do not generate new Kitty escape sequences.\n\t\t\tprocess.stdout.write(\"\\x1b[<u\");\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\n\t\tconst previousHandler = this.inputHandler;\n\t\tthis.inputHandler = undefined;\n\n\t\tlet lastDataTime = Date.now();\n\t\tconst onData = () => {\n\t\t\tlastDataTime = Date.now();\n\t\t};\n\n\t\tprocess.stdin.on(\"data\", onData);\n\t\tconst endTime = Date.now() + maxMs;\n\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst timeLeft = endTime - now;\n\t\t\t\tif (timeLeft <= 0) break;\n\t\t\t\tif (now - lastDataTime >= idleMs) break;\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, Math.min(idleMs, timeLeft)));\n\t\t\t}\n\t\t} finally {\n\t\t\tprocess.stdin.removeListener(\"data\", onData);\n\t\t\tthis.inputHandler = previousHandler;\n\t\t}\n\t}\n\n\tstop(): void {\n\t\t// Disable bracketed paste mode\n\t\tprocess.stdout.write(\"\\x1b[?2004l\");\n\n\t\t// Disable Kitty keyboard protocol if not already done by drainInput()\n\t\tif (this._kittyProtocolActive) {\n\t\t\tprocess.stdout.write(\"\\x1b[<u\");\n\t\t\tthis._kittyProtocolActive = false;\n\t\t\tsetKittyProtocolActive(false);\n\t\t}\n\n\t\t// Clean up StdinBuffer\n\t\tif (this.stdinBuffer) {\n\t\t\tthis.stdinBuffer.destroy();\n\t\t\tthis.stdinBuffer = undefined;\n\t\t}\n\n\t\t// Remove event handlers\n\t\tif (this.stdinDataHandler) {\n\t\t\tprocess.stdin.removeListener(\"data\", this.stdinDataHandler);\n\t\t\tthis.stdinDataHandler = undefined;\n\t\t}\n\t\tthis.inputHandler = undefined;\n\t\tif (this.resizeHandler) {\n\t\t\tprocess.stdout.removeListener(\"resize\", this.resizeHandler);\n\t\t\tthis.resizeHandler = undefined;\n\t\t}\n\n\t\t// Pause stdin to prevent any buffered input (e.g., Ctrl+D) from being\n\t\t// re-interpreted after raw mode is disabled. This fixes a race condition\n\t\t// where Ctrl+D could close the parent shell over SSH.\n\t\tprocess.stdin.pause();\n\n\t\t// Restore raw mode state\n\t\tif (process.stdin.setRawMode) {\n\t\t\tprocess.stdin.setRawMode(this.wasRaw);\n\t\t}\n\t}\n\n\twrite(data: string): void {\n\t\tprocess.stdout.write(data);\n\t\tif (this.writeLogPath) {\n\t\t\ttry {\n\t\t\t\tfs.appendFileSync(this.writeLogPath, data, { encoding: \"utf8\" });\n\t\t\t} catch {\n\t\t\t\t// Ignore logging errors\n\t\t\t}\n\t\t}\n\t}\n\n\tget columns(): number {\n\t\treturn process.stdout.columns || 80;\n\t}\n\n\tget rows(): number {\n\t\treturn process.stdout.rows || 24;\n\t}\n\n\tmoveBy(lines: number): void {\n\t\tif (lines > 0) {\n\t\t\t// Move down\n\t\t\tprocess.stdout.write(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\t// Move up\n\t\t\tprocess.stdout.write(`\\x1b[${-lines}A`);\n\t\t}\n\t\t// lines === 0: no movement\n\t}\n\n\thideCursor(): void {\n\t\tprocess.stdout.write(\"\\x1b[?25l\");\n\t}\n\n\tshowCursor(): void {\n\t\tprocess.stdout.write(\"\\x1b[?25h\");\n\t}\n\n\tclearLine(): void {\n\t\tprocess.stdout.write(\"\\x1b[K\");\n\t}\n\n\tclearFromCursor(): void {\n\t\tprocess.stdout.write(\"\\x1b[J\");\n\t}\n\n\tclearScreen(): void {\n\t\tprocess.stdout.write(\"\\x1b[2J\\x1b[H\"); // Clear screen and move to home (1,1)\n\t}\n\n\tsetTitle(title: string): void {\n\t\t// OSC 0;title BEL - set terminal window title\n\t\tprocess.stdout.write(`\\x1b]0;${title}\\x07`);\n\t}\n}\n"]}
|
package/dist/tui.d.ts
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal TUI implementation with differential rendering
|
|
3
|
+
*/
|
|
4
|
+
import type { Terminal } from "./terminal.js";
|
|
5
|
+
import { visibleWidth } from "./utils.js";
|
|
6
|
+
/**
|
|
7
|
+
* Component interface - all components must implement this
|
|
8
|
+
*/
|
|
9
|
+
export interface Component {
|
|
10
|
+
/**
|
|
11
|
+
* Render the component to lines for the given viewport width
|
|
12
|
+
* @param width - Current viewport width
|
|
13
|
+
* @returns Array of strings, each representing a line
|
|
14
|
+
*/
|
|
15
|
+
render(width: number): string[];
|
|
16
|
+
/**
|
|
17
|
+
* Optional handler for keyboard input when component has focus
|
|
18
|
+
*/
|
|
19
|
+
handleInput?(data: string): void;
|
|
20
|
+
/**
|
|
21
|
+
* If true, component receives key release events (Kitty protocol).
|
|
22
|
+
* Default is false - release events are filtered out.
|
|
23
|
+
*/
|
|
24
|
+
wantsKeyRelease?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Invalidate any cached rendering state.
|
|
27
|
+
* Called when theme changes or when component needs to re-render from scratch.
|
|
28
|
+
*/
|
|
29
|
+
invalidate(): void;
|
|
30
|
+
}
|
|
31
|
+
type InputListenerResult = {
|
|
32
|
+
consume?: boolean;
|
|
33
|
+
data?: string;
|
|
34
|
+
} | undefined;
|
|
35
|
+
type InputListener = (data: string) => InputListenerResult;
|
|
36
|
+
/**
|
|
37
|
+
* Interface for components that can receive focus and display a hardware cursor.
|
|
38
|
+
* When focused, the component should emit CURSOR_MARKER at the cursor position
|
|
39
|
+
* in its render output. TUI will find this marker and position the hardware
|
|
40
|
+
* cursor there for proper IME candidate window positioning.
|
|
41
|
+
*/
|
|
42
|
+
export interface Focusable {
|
|
43
|
+
/** Set by TUI when focus changes. Component should emit CURSOR_MARKER when true. */
|
|
44
|
+
focused: boolean;
|
|
45
|
+
}
|
|
46
|
+
/** Type guard to check if a component implements Focusable */
|
|
47
|
+
export declare function isFocusable(component: Component | null): component is Component & Focusable;
|
|
48
|
+
/**
|
|
49
|
+
* Cursor position marker - APC (Application Program Command) sequence.
|
|
50
|
+
* This is a zero-width escape sequence that terminals ignore.
|
|
51
|
+
* Components emit this at the cursor position when focused.
|
|
52
|
+
* TUI finds and strips this marker, then positions the hardware cursor there.
|
|
53
|
+
*/
|
|
54
|
+
export declare const CURSOR_MARKER = "\u001B_pi:c\u0007";
|
|
55
|
+
export { visibleWidth };
|
|
56
|
+
/**
|
|
57
|
+
* Anchor position for overlays
|
|
58
|
+
*/
|
|
59
|
+
export type OverlayAnchor = "center" | "top-left" | "top-right" | "bottom-left" | "bottom-right" | "top-center" | "bottom-center" | "left-center" | "right-center";
|
|
60
|
+
/**
|
|
61
|
+
* Margin configuration for overlays
|
|
62
|
+
*/
|
|
63
|
+
export interface OverlayMargin {
|
|
64
|
+
top?: number;
|
|
65
|
+
right?: number;
|
|
66
|
+
bottom?: number;
|
|
67
|
+
left?: number;
|
|
68
|
+
}
|
|
69
|
+
/** Value that can be absolute (number) or percentage (string like "50%") */
|
|
70
|
+
export type SizeValue = number | `${number}%`;
|
|
71
|
+
/**
|
|
72
|
+
* Options for overlay positioning and sizing.
|
|
73
|
+
* Values can be absolute numbers or percentage strings (e.g., "50%").
|
|
74
|
+
*/
|
|
75
|
+
export interface OverlayOptions {
|
|
76
|
+
/** Width in columns, or percentage of terminal width (e.g., "50%") */
|
|
77
|
+
width?: SizeValue;
|
|
78
|
+
/** Minimum width in columns */
|
|
79
|
+
minWidth?: number;
|
|
80
|
+
/** Maximum height in rows, or percentage of terminal height (e.g., "50%") */
|
|
81
|
+
maxHeight?: SizeValue;
|
|
82
|
+
/** Anchor point for positioning (default: 'center') */
|
|
83
|
+
anchor?: OverlayAnchor;
|
|
84
|
+
/** Horizontal offset from anchor position (positive = right) */
|
|
85
|
+
offsetX?: number;
|
|
86
|
+
/** Vertical offset from anchor position (positive = down) */
|
|
87
|
+
offsetY?: number;
|
|
88
|
+
/** Row position: absolute number, or percentage (e.g., "25%" = 25% from top) */
|
|
89
|
+
row?: SizeValue;
|
|
90
|
+
/** Column position: absolute number, or percentage (e.g., "50%" = centered horizontally) */
|
|
91
|
+
col?: SizeValue;
|
|
92
|
+
/** Margin from terminal edges. Number applies to all sides. */
|
|
93
|
+
margin?: OverlayMargin | number;
|
|
94
|
+
/**
|
|
95
|
+
* Control overlay visibility based on terminal dimensions.
|
|
96
|
+
* If provided, overlay is only rendered when this returns true.
|
|
97
|
+
* Called each render cycle with current terminal dimensions.
|
|
98
|
+
*/
|
|
99
|
+
visible?: (termWidth: number, termHeight: number) => boolean;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Handle returned by showOverlay for controlling the overlay
|
|
103
|
+
*/
|
|
104
|
+
export interface OverlayHandle {
|
|
105
|
+
/** Permanently remove the overlay (cannot be shown again) */
|
|
106
|
+
hide(): void;
|
|
107
|
+
/** Temporarily hide or show the overlay */
|
|
108
|
+
setHidden(hidden: boolean): void;
|
|
109
|
+
/** Check if overlay is temporarily hidden */
|
|
110
|
+
isHidden(): boolean;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Container - a component that contains other components
|
|
114
|
+
*/
|
|
115
|
+
export declare class Container implements Component {
|
|
116
|
+
children: Component[];
|
|
117
|
+
addChild(component: Component): void;
|
|
118
|
+
removeChild(component: Component): void;
|
|
119
|
+
clear(): void;
|
|
120
|
+
invalidate(): void;
|
|
121
|
+
render(width: number): string[];
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* TUI - Main class for managing terminal UI with differential rendering
|
|
125
|
+
*/
|
|
126
|
+
export declare class TUI extends Container {
|
|
127
|
+
terminal: Terminal;
|
|
128
|
+
private previousLines;
|
|
129
|
+
private previousWidth;
|
|
130
|
+
private focusedComponent;
|
|
131
|
+
private inputListeners;
|
|
132
|
+
/** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
|
|
133
|
+
onDebug?: () => void;
|
|
134
|
+
private renderRequested;
|
|
135
|
+
private cursorRow;
|
|
136
|
+
private hardwareCursorRow;
|
|
137
|
+
private inputBuffer;
|
|
138
|
+
private cellSizeQueryPending;
|
|
139
|
+
private showHardwareCursor;
|
|
140
|
+
private clearOnShrink;
|
|
141
|
+
private maxLinesRendered;
|
|
142
|
+
private previousViewportTop;
|
|
143
|
+
private fullRedrawCount;
|
|
144
|
+
private stopped;
|
|
145
|
+
private overlayStack;
|
|
146
|
+
constructor(terminal: Terminal, showHardwareCursor?: boolean);
|
|
147
|
+
get fullRedraws(): number;
|
|
148
|
+
getShowHardwareCursor(): boolean;
|
|
149
|
+
setShowHardwareCursor(enabled: boolean): void;
|
|
150
|
+
getClearOnShrink(): boolean;
|
|
151
|
+
/**
|
|
152
|
+
* Set whether to trigger full re-render when content shrinks.
|
|
153
|
+
* When true (default), empty rows are cleared when content shrinks.
|
|
154
|
+
* When false, empty rows remain (reduces redraws on slower terminals).
|
|
155
|
+
*/
|
|
156
|
+
setClearOnShrink(enabled: boolean): void;
|
|
157
|
+
setFocus(component: Component | null): void;
|
|
158
|
+
/**
|
|
159
|
+
* Show an overlay component with configurable positioning and sizing.
|
|
160
|
+
* Returns a handle to control the overlay's visibility.
|
|
161
|
+
*/
|
|
162
|
+
showOverlay(component: Component, options?: OverlayOptions): OverlayHandle;
|
|
163
|
+
/** Hide the topmost overlay and restore previous focus. */
|
|
164
|
+
hideOverlay(): void;
|
|
165
|
+
/** Check if there are any visible overlays */
|
|
166
|
+
hasOverlay(): boolean;
|
|
167
|
+
/** Check if an overlay entry is currently visible */
|
|
168
|
+
private isOverlayVisible;
|
|
169
|
+
/** Find the topmost visible overlay, if any */
|
|
170
|
+
private getTopmostVisibleOverlay;
|
|
171
|
+
invalidate(): void;
|
|
172
|
+
start(): void;
|
|
173
|
+
addInputListener(listener: InputListener): () => void;
|
|
174
|
+
removeInputListener(listener: InputListener): void;
|
|
175
|
+
private queryCellSize;
|
|
176
|
+
stop(): void;
|
|
177
|
+
requestRender(force?: boolean): void;
|
|
178
|
+
private handleInput;
|
|
179
|
+
private parseCellSizeResponse;
|
|
180
|
+
/**
|
|
181
|
+
* Resolve overlay layout from options.
|
|
182
|
+
* Returns { width, row, col, maxHeight } for rendering.
|
|
183
|
+
*/
|
|
184
|
+
private resolveOverlayLayout;
|
|
185
|
+
private resolveAnchorRow;
|
|
186
|
+
private resolveAnchorCol;
|
|
187
|
+
/** Composite all overlays into content lines (in stack order, later = on top). */
|
|
188
|
+
private compositeOverlays;
|
|
189
|
+
private static readonly SEGMENT_RESET;
|
|
190
|
+
private applyLineResets;
|
|
191
|
+
/** Splice overlay content into a base line at a specific column. Single-pass optimized. */
|
|
192
|
+
private compositeLineAt;
|
|
193
|
+
/**
|
|
194
|
+
* Find and extract cursor position from rendered lines.
|
|
195
|
+
* Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
|
|
196
|
+
* Only scans the bottom terminal height lines (visible viewport).
|
|
197
|
+
* @param lines - Rendered lines to search
|
|
198
|
+
* @param height - Terminal height (visible viewport size)
|
|
199
|
+
* @returns Cursor position { row, col } or null if no marker found
|
|
200
|
+
*/
|
|
201
|
+
private extractCursorPosition;
|
|
202
|
+
private doRender;
|
|
203
|
+
/**
|
|
204
|
+
* Position the hardware cursor for IME candidate window.
|
|
205
|
+
* @param cursorPos The cursor position extracted from rendered output, or null
|
|
206
|
+
* @param totalLines Total number of rendered lines
|
|
207
|
+
*/
|
|
208
|
+
private positionHardwareCursor;
|
|
209
|
+
}
|
|
210
|
+
//# sourceMappingURL=tui.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tui.d.ts","sourceRoot":"","sources":["../src/tui.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,OAAO,EAAkD,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1F;;GAEG;AACH,MAAM,WAAW,SAAS;IACzB;;;;OAIG;IACH,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAEhC;;OAEG;IACH,WAAW,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAEjC;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B;;;OAGG;IACH,UAAU,IAAI,IAAI,CAAC;CACnB;AAED,KAAK,mBAAmB,GAAG;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC;AAC5E,KAAK,aAAa,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,mBAAmB,CAAC;AAE3D;;;;;GAKG;AACH,MAAM,WAAW,SAAS;IACzB,oFAAoF;IACpF,OAAO,EAAE,OAAO,CAAC;CACjB;AAED,8DAA8D;AAC9D,wBAAgB,WAAW,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI,GAAG,SAAS,IAAI,SAAS,GAAG,SAAS,CAE3F;AAED;;;;;GAKG;AACH,eAAO,MAAM,aAAa,sBAAkB,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,CAAC;AAExB;;GAEG;AACH,MAAM,MAAM,aAAa,GACtB,QAAQ,GACR,UAAU,GACV,WAAW,GACX,aAAa,GACb,cAAc,GACd,YAAY,GACZ,eAA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OAGG;IACH,WAAW,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,aAAa,CA6CzE;IAED,2DAA2D;IAC3D,WAAW,IAAI,IAAI,CAQlB;IAED,8CAA8C;IAC9C,UAAU,IAAI,OAAO,CAEpB;IAED,qDAAqD;IACrD,OAAO,CAAC,gBAAgB;IAQxB,+CAA+C;IAC/C,OAAO,CAAC,wBAAwB;IASvB,UAAU,IAAI,IAAI,CAG1B;IAED,KAAK,IAAI,IAAI,CASZ;IAED,gBAAgB,CAAC,QAAQ,EAAE,aAAa,GAAG,MAAM,IAAI,CAKpD;IAED,mBAAmB,CAAC,QAAQ,EAAE,aAAa,GAAG,IAAI,CAEjD;IAED,OAAO,CAAC,aAAa;IAWrB,IAAI,IAAI,IAAI,CAgBX;IAED,aAAa,CAAC,KAAK,UAAQ,GAAG,IAAI,CAejC;IAED,OAAO,CAAC,WAAW;IA0DnB,OAAO,CAAC,qBAAqB;IA0C7B;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAoG5B,OAAO,CAAC,gBAAgB;IAiBxB,OAAO,CAAC,gBAAgB;IAiBxB,kFAAkF;IAClF,OAAO,CAAC,iBAAiB;IA4EzB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAyB;IAE9D,OAAO,CAAC,eAAe;IAWvB,2FAA2F;IAC3F,OAAO,CAAC,eAAe;IAkDvB;;;;;;;OAOG;IACH,OAAO,CAAC,qBAAqB;IAoB7B,OAAO,CAAC,QAAQ;IA6ShB;;;;OAIG;IACH,OAAO,CAAC,sBAAsB;CAgC9B","sourcesContent":["/**\n * Minimal TUI implementation with differential rendering\n */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { isKeyRelease, matchesKey } from \"./keys.js\";\nimport type { Terminal } from \"./terminal.js\";\nimport { getCapabilities, isImageLine, setCellDimensions } from \"./terminal-image.js\";\nimport { extractSegments, sliceByColumn, sliceWithWidth, visibleWidth } from \"./utils.js\";\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 */\n\thandleInput?(data: string): 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\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\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}\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}\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\tlines.push(...child.render(width));\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 previousWidth = 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 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 inputBuffer = \"\"; // Buffer for parsing terminal responses\n\tprivate cellSizeQueryPending = false;\n\tprivate showHardwareCursor = process.env.PI_HARDWARE_CURSOR === \"1\";\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\n\t// Overlay stack for modal components rendered on top of base content\n\tprivate overlayStack: {\n\t\tcomponent: Component;\n\t\toptions?: OverlayOptions;\n\t\tpreFocus: Component | null;\n\t\thidden: boolean;\n\t}[] = [];\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\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\t// Clear focused flag on old component\n\t\tif (isFocusable(this.focusedComponent)) {\n\t\t\tthis.focusedComponent.focused = false;\n\t\t}\n\n\t\tthis.focusedComponent = component;\n\n\t\t// Set focused flag on new component\n\t\tif (isFocusable(component)) {\n\t\t\tcomponent.focused = true;\n\t\t}\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 = { component, options, preFocus: this.focusedComponent, hidden: false };\n\t\tthis.overlayStack.push(entry);\n\t\t// Only focus if overlay is actually visible\n\t\tif (this.isOverlayVisible(entry)) {\n\t\t\tthis.setFocus(component);\n\t\t}\n\t\tthis.terminal.hideCursor();\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.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.terminal.hideCursor();\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\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 (this.isOverlayVisible(entry)) {\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};\n\t}\n\n\t/** Hide the topmost overlay and restore previous focus. */\n\thideOverlay(): void {\n\t\tconst overlay = this.overlayStack.pop();\n\t\tif (!overlay) return;\n\t\t// Find topmost visible overlay, or fall back to preFocus\n\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\tthis.setFocus(topVisible?.component ?? overlay.preFocus);\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: (typeof this.overlayStack)[number]): 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 topmost visible overlay, if any */\n\tprivate getTopmostVisibleOverlay(): (typeof this.overlayStack)[number] | undefined {\n\t\tfor (let i = this.overlayStack.length - 1; i >= 0; i--) {\n\t\t\tif (this.isOverlayVisible(this.overlayStack[i])) {\n\t\t\t\treturn this.overlayStack[i];\n\t\t\t}\n\t\t}\n\t\treturn undefined;\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\tthis.terminal.hideCursor();\n\t\tthis.queryCellSize();\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.cellSizeQueryPending = true;\n\t\tthis.terminal.write(\"\\x1b[16t\");\n\t}\n\n\tstop(): void {\n\t\tthis.stopped = true;\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\tthis.terminal.stop();\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.cursorRow = 0;\n\t\t\tthis.hardwareCursorRow = 0;\n\t\t\tthis.maxLinesRendered = 0;\n\t\t\tthis.previousViewportTop = 0;\n\t\t}\n\t\tif (this.renderRequested) return;\n\t\tthis.renderRequested = true;\n\t\tprocess.nextTick(() => {\n\t\t\tthis.renderRequested = false;\n\t\t\tthis.doRender();\n\t\t});\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// If we're waiting for cell size response, buffer input and parse\n\t\tif (this.cellSizeQueryPending) {\n\t\t\tthis.inputBuffer += data;\n\t\t\tconst filtered = this.parseCellSizeResponse();\n\t\t\tif (filtered.length === 0) return;\n\t\t\tdata = filtered;\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\t// No visible overlays, restore to preFocus\n\t\t\t\tthis.setFocus(focusedOverlay.preFocus);\n\t\t\t}\n\t\t}\n\n\t\t// Pass input to focused component (including Ctrl+C)\n\t\t// The focused component can decide how to handle Ctrl+C\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\tthis.focusedComponent.handleInput(data);\n\t\t\tthis.requestRender();\n\t\t}\n\t}\n\n\tprivate parseCellSizeResponse(): string {\n\t\t// Response format: ESC [ 6 ; height ; width t\n\t\t// Match the response pattern\n\t\tconst responsePattern = /\\x1b\\[6;(\\d+);(\\d+)t/;\n\t\tconst match = this.inputBuffer.match(responsePattern);\n\n\t\tif (match) {\n\t\t\tconst heightPx = parseInt(match[1], 10);\n\t\t\tconst widthPx = parseInt(match[2], 10);\n\n\t\t\tif (heightPx > 0 && widthPx > 0) {\n\t\t\t\tsetCellDimensions({ widthPx, heightPx });\n\t\t\t\t// Invalidate all components so images re-render with correct dimensions\n\t\t\t\tthis.invalidate();\n\t\t\t\tthis.requestRender();\n\t\t\t}\n\n\t\t\t// Remove the response from buffer\n\t\t\tthis.inputBuffer = this.inputBuffer.replace(responsePattern, \"\");\n\t\t\tthis.cellSizeQueryPending = false;\n\t\t}\n\n\t\t// Check if we have a partial cell size response starting (wait for more data)\n\t\t// Patterns that could be incomplete cell size response: \\x1b, \\x1b[, \\x1b[6, \\x1b[6;...(no t yet)\n\t\tconst partialCellSizePattern = /\\x1b(\\[6?;?[\\d;]*)?$/;\n\t\tif (partialCellSizePattern.test(this.inputBuffer)) {\n\t\t\t// Check if it's actually a complete different escape sequence (ends with a letter)\n\t\t\t// Cell size response ends with 't', Kitty keyboard ends with 'u', arrows end with A-D, etc.\n\t\t\tconst lastChar = this.inputBuffer[this.inputBuffer.length - 1];\n\t\t\tif (!/[a-zA-Z~]/.test(lastChar)) {\n\t\t\t\t// Doesn't end with a terminator, might be incomplete - wait for more\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t}\n\n\t\t// No cell size response found, return buffered data as user input\n\t\tconst result = this.inputBuffer;\n\t\tthis.inputBuffer = \"\";\n\t\tthis.cellSizeQueryPending = false; // Give up waiting\n\t\treturn result;\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 (in stack order, later = on top). */\n\tprivate compositeOverlays(lines: string[], termWidth: number, termHeight: number): string[] {\n\t\tif (this.overlayStack.length === 0) return lines;\n\t\tconst result = [...lines];\n\n\t\t// Pre-render all visible overlays and calculate positions\n\t\tconst rendered: { overlayLines: string[]; row: number; col: number; w: number }[] = [];\n\t\tlet minLinesNeeded = result.length;\n\n\t\tfor (const entry of this.overlayStack) {\n\t\t\t// Skip invisible overlays (hidden or visible() returns false)\n\t\t\tif (!this.isOverlayVisible(entry)) continue;\n\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({ overlayLines, row, col, w: width });\n\t\t\tminLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);\n\t\t}\n\n\t\t// Ensure result covers the terminal working area to keep overlay positioning stable across resizes.\n\t\t// maxLinesRendered can exceed current content length after a shrink; pad to keep viewportStart consistent.\n\t\tconst workingHeight = Math.max(this.maxLinesRendered, 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// Track which lines were modified for final verification\n\t\tconst modifiedLines = new Set<number>();\n\n\t\t// Composite each overlay\n\t\tfor (const { overlayLines, row, col, w } 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\tresult[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);\n\t\t\t\t\tmodifiedLines.add(idx);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Final verification: ensure no composited line exceeds terminal width\n\t\t// This is a belt-and-suspenders safeguard - compositeLineAt should already\n\t\t// guarantee this, but we verify here to prevent crashes from any edge cases\n\t\t// Only check lines that were actually modified (optimization)\n\t\tfor (const idx of modifiedLines) {\n\t\t\tconst lineWidth = visibleWidth(result[idx]);\n\t\t\tif (lineWidth > termWidth) {\n\t\t\t\tresult[idx] = sliceByColumn(result[idx], 0, termWidth, true);\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] = line + reset;\n\t\t\t}\n\t\t}\n\t\treturn lines;\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 doRender(): void {\n\t\tif (this.stopped) return;\n\t\tconst width = this.terminal.columns;\n\t\tconst height = this.terminal.rows;\n\t\tlet viewportTop = Math.max(0, this.maxLinesRendered - height);\n\t\tlet prevViewportTop = this.previousViewportTop;\n\t\tlet hardwareCursorRow = this.hardwareCursorRow;\n\t\tconst computeLineDiff = (targetRow: number): number => {\n\t\t\tconst currentScreenRow = hardwareCursorRow - prevViewportTop;\n\t\t\tconst targetScreenRow = targetRow - viewportTop;\n\t\t\treturn targetScreenRow - currentScreenRow;\n\t\t};\n\n\t\t// Render all components to get new lines\n\t\tlet newLines = this.render(width);\n\n\t\t// Composite overlays into the rendered lines (before differential compare)\n\t\tif (this.overlayStack.length > 0) {\n\t\t\tnewLines = this.compositeOverlays(newLines, width, height);\n\t\t}\n\n\t\t// Extract cursor position before applying line resets (marker must be found first)\n\t\tconst cursorPos = this.extractCursorPosition(newLines, height);\n\n\t\tnewLines = this.applyLineResets(newLines);\n\n\t\t// Width changed - need full re-render (line wrapping changes)\n\t\tconst widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;\n\n\t\t// Helper to clear scrollback and viewport and render all new lines\n\t\tconst fullRender = (clear: boolean): void => {\n\t\t\tthis.fullRedrawCount += 1;\n\t\t\tlet buffer = \"\\x1b[?2026h\"; // Begin synchronized output\n\t\t\tif (clear) buffer += \"\\x1b[3J\\x1b[2J\\x1b[H\"; // Clear scrollback, screen, and home\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}\n\t\t\tbuffer += \"\\x1b[?2026l\"; // End synchronized output\n\t\t\tthis.terminal.write(buffer);\n\t\t\tthis.cursorRow = Math.max(0, newLines.length - 1);\n\t\t\tthis.hardwareCursorRow = this.cursorRow;\n\t\t\t// Reset max lines when clearing, otherwise track growth\n\t\t\tif (clear) {\n\t\t\t\tthis.maxLinesRendered = newLines.length;\n\t\t\t} else {\n\t\t\t\tthis.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);\n\t\t\t}\n\t\t\tthis.previousViewportTop = Math.max(0, this.maxLinesRendered - height);\n\t\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\t\t\tthis.previousLines = newLines;\n\t\t\tthis.previousWidth = width;\n\t\t};\n\n\t\tconst debugRedraw = process.env.PI_DEBUG_REDRAW === \"1\";\n\t\tconst logRedraw = (reason: string): void => {\n\t\t\tif (!debugRedraw) return;\n\t\t\tconst logPath = path.join(os.homedir(), \".pi\", \"agent\", \"pi-debug.log\");\n\t\t\tconst msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\\n`;\n\t\t\tfs.appendFileSync(logPath, msg);\n\t\t};\n\n\t\t// First render - just output everything without clearing (assumes clean screen)\n\t\tif (this.previousLines.length === 0 && !widthChanged) {\n\t\t\tlogRedraw(\"first render\");\n\t\t\tfullRender(false);\n\t\t\treturn;\n\t\t}\n\n\t\t// Width changed - full re-render (line wrapping changes)\n\t\tif (widthChanged) {\n\t\t\tlogRedraw(`width changed (${this.previousWidth} -> ${width})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Content shrunk below the working area and no overlays - re-render to clear empty rows\n\t\t// (overlays need the padding, so only do this when no overlays are active)\n\t\t// Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var\n\t\tif (this.clearOnShrink && newLines.length < this.maxLinesRendered && this.overlayStack.length === 0) {\n\t\t\tlogRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Find first and last changed lines\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\n\t\t\tif (oldLine !== newLine) {\n\t\t\t\tif (firstChanged === -1) {\n\t\t\t\t\tfirstChanged = i;\n\t\t\t\t}\n\t\t\t\tlastChanged = i;\n\t\t\t}\n\t\t}\n\t\tconst appendedLines = newLines.length > this.previousLines.length;\n\t\tif (appendedLines) {\n\t\t\tif (firstChanged === -1) {\n\t\t\t\tfirstChanged = this.previousLines.length;\n\t\t\t}\n\t\t\tlastChanged = newLines.length - 1;\n\t\t}\n\t\tconst appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;\n\n\t\t// No changes - but still need to update hardware cursor position if it moved\n\t\tif (firstChanged === -1) {\n\t\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\t\t\tthis.previousViewportTop = Math.max(0, this.maxLinesRendered - height);\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\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\tconst lineDiff = computeLineDiff(targetRow);\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\tlogRedraw(`extraLines > height (${extraLines} > ${height})`);\n\t\t\t\t\tfullRender(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (extraLines > 0) {\n\t\t\t\t\tbuffer += \"\\x1b[1B\";\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\tif (extraLines > 0) {\n\t\t\t\t\tbuffer += `\\x1b[${extraLines}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.positionHardwareCursor(cursorPos, newLines.length);\n\t\t\tthis.previousLines = newLines;\n\t\t\tthis.previousWidth = width;\n\t\t\tthis.previousViewportTop = Math.max(0, this.maxLinesRendered - height);\n\t\t\treturn;\n\t\t}\n\n\t\t// Check if firstChanged is above what was previously visible\n\t\t// Use previousLines.length (not maxLinesRendered) to avoid false positives after content shrinks\n\t\tconst previousContentViewportTop = Math.max(0, this.previousLines.length - height);\n\t\tif (firstChanged < previousContentViewportTop) {\n\t\t\t// First change is above previous viewport - need full re-render\n\t\t\tlogRedraw(`firstChanged < viewportTop (${firstChanged} < ${previousContentViewportTop})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Render from first changed line to end\n\t\t// Build buffer with all updates wrapped in synchronized output\n\t\tlet buffer = \"\\x1b[?2026h\"; // Begin synchronized output\n\t\tconst prevViewportBottom = prevViewportTop + height - 1;\n\t\tconst moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;\n\t\tif (moveTargetRow > prevViewportBottom) {\n\t\t\tconst currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));\n\t\t\tconst moveToBottom = height - 1 - currentScreenRow;\n\t\t\tif (moveToBottom > 0) {\n\t\t\t\tbuffer += `\\x1b[${moveToBottom}B`;\n\t\t\t}\n\t\t\tconst scroll = moveTargetRow - prevViewportBottom;\n\t\t\tbuffer += \"\\r\\n\".repeat(scroll);\n\t\t\tprevViewportTop += scroll;\n\t\t\tviewportTop += scroll;\n\t\t\thardwareCursorRow = moveTargetRow;\n\t\t}\n\n\t\t// Move cursor to first changed line (use hardwareCursorRow for actual position)\n\t\tconst lineDiff = computeLineDiff(moveTargetRow);\n\t\tif (lineDiff > 0) {\n\t\t\tbuffer += `\\x1b[${lineDiff}B`; // Move down\n\t\t} else if (lineDiff < 0) {\n\t\t\tbuffer += `\\x1b[${-lineDiff}A`; // Move up\n\t\t}\n\n\t\tbuffer += appendStart ? \"\\r\\n\" : \"\\r\"; // Move to column 0\n\n\t\t// Only render changed lines (firstChanged to lastChanged), not all lines to end\n\t\t// This reduces flicker when only a single line changes (e.g., spinner animation)\n\t\tconst renderEnd = Math.min(lastChanged, newLines.length - 1);\n\t\tfor (let i = firstChanged; i <= renderEnd; i++) {\n\t\t\tif (i > firstChanged) buffer += \"\\r\\n\";\n\t\t\tbuffer += \"\\x1b[2K\"; // Clear current line\n\t\t\tconst line = newLines[i];\n\t\t\tconst isImage = isImageLine(line);\n\t\t\tif (!isImage && visibleWidth(line) > width) {\n\t\t\t\t// Log all lines to crash file for debugging\n\t\t\t\tconst crashLogPath = path.join(os.homedir(), \".pi\", \"agent\", \"pi-crash.log\");\n\t\t\t\tconst crashData = [\n\t\t\t\t\t`Crash at ${new Date().toISOString()}`,\n\t\t\t\t\t`Terminal width: ${width}`,\n\t\t\t\t\t`Line ${i} visible width: ${visibleWidth(line)}`,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"=== All rendered lines ===\",\n\t\t\t\t\t...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),\n\t\t\t\t\t\"\",\n\t\t\t\t].join(\"\\n\");\n\t\t\t\tfs.mkdirSync(path.dirname(crashLogPath), { recursive: true });\n\t\t\t\tfs.writeFileSync(crashLogPath, crashData);\n\n\t\t\t\t// Clean up terminal state before throwing\n\t\t\t\tthis.stop();\n\n\t\t\t\tconst errorMsg = [\n\t\t\t\t\t`Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"This is likely caused by a custom TUI component not truncating its output.\",\n\t\t\t\t\t\"Use visibleWidth() to measure and truncateToWidth() to truncate lines.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t`Debug log written to: ${crashLogPath}`,\n\t\t\t\t].join(\"\\n\");\n\t\t\t\tthrow new Error(errorMsg);\n\t\t\t}\n\t\t\tbuffer += line;\n\t\t}\n\n\t\t// Track where cursor ended up after rendering\n\t\tlet finalCursorRow = renderEnd;\n\n\t\t// If we had more lines before, clear them and move cursor back\n\t\tif (this.previousLines.length > newLines.length) {\n\t\t\t// Move to end of new content first if we stopped before it\n\t\t\tif (renderEnd < newLines.length - 1) {\n\t\t\t\tconst moveDown = newLines.length - 1 - renderEnd;\n\t\t\t\tbuffer += `\\x1b[${moveDown}B`;\n\t\t\t\tfinalCursorRow = newLines.length - 1;\n\t\t\t}\n\t\t\tconst extraLines = this.previousLines.length - newLines.length;\n\t\t\tfor (let i = newLines.length; i < this.previousLines.length; i++) {\n\t\t\t\tbuffer += \"\\r\\n\\x1b[2K\";\n\t\t\t}\n\t\t\t// Move cursor back to end of new content\n\t\t\tbuffer += `\\x1b[${extraLines}A`;\n\t\t}\n\n\t\tbuffer += \"\\x1b[?2026l\"; // End synchronized output\n\n\t\tif (process.env.PI_TUI_DEBUG === \"1\") {\n\t\t\tconst debugDir = \"/tmp/tui\";\n\t\t\tfs.mkdirSync(debugDir, { recursive: true });\n\t\t\tconst debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);\n\t\t\tconst debugData = [\n\t\t\t\t`firstChanged: ${firstChanged}`,\n\t\t\t\t`viewportTop: ${viewportTop}`,\n\t\t\t\t`cursorRow: ${this.cursorRow}`,\n\t\t\t\t`height: ${height}`,\n\t\t\t\t`lineDiff: ${lineDiff}`,\n\t\t\t\t`hardwareCursorRow: ${hardwareCursorRow}`,\n\t\t\t\t`renderEnd: ${renderEnd}`,\n\t\t\t\t`finalCursorRow: ${finalCursorRow}`,\n\t\t\t\t`cursorPos: ${JSON.stringify(cursorPos)}`,\n\t\t\t\t`newLines.length: ${newLines.length}`,\n\t\t\t\t`previousLines.length: ${this.previousLines.length}`,\n\t\t\t\t\"\",\n\t\t\t\t\"=== newLines ===\",\n\t\t\t\tJSON.stringify(newLines, null, 2),\n\t\t\t\t\"\",\n\t\t\t\t\"=== previousLines ===\",\n\t\t\t\tJSON.stringify(this.previousLines, null, 2),\n\t\t\t\t\"\",\n\t\t\t\t\"=== buffer ===\",\n\t\t\t\tJSON.stringify(buffer),\n\t\t\t].join(\"\\n\");\n\t\t\tfs.writeFileSync(debugPath, debugData);\n\t\t}\n\n\t\t// Write entire buffer at once\n\t\tthis.terminal.write(buffer);\n\n\t\t// Track cursor position for next render\n\t\t// cursorRow tracks end of content (for viewport calculation)\n\t\t// hardwareCursorRow tracks actual terminal cursor position (for movement)\n\t\tthis.cursorRow = Math.max(0, newLines.length - 1);\n\t\tthis.hardwareCursorRow = finalCursorRow;\n\t\t// Track terminal's working area (grows but doesn't shrink unless cleared)\n\t\tthis.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);\n\t\tthis.previousViewportTop = Math.max(0, this.maxLinesRendered - height);\n\n\t\t// Position hardware cursor for IME\n\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\n\t\tthis.previousLines = newLines;\n\t\tthis.previousWidth = width;\n\t}\n\n\t/**\n\t * Position the hardware cursor for IME candidate window.\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 positionHardwareCursor(cursorPos: { row: number; col: number } | null, totalLines: number): void {\n\t\tif (!cursorPos || totalLines <= 0) {\n\t\t\tthis.terminal.hideCursor();\n\t\t\treturn;\n\t\t}\n\n\t\t// Clamp cursor position to valid range\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\t// Move cursor from current position to target\n\t\tconst rowDelta = targetRow - this.hardwareCursorRow;\n\t\tlet buffer = \"\";\n\t\tif (rowDelta > 0) {\n\t\t\tbuffer += `\\x1b[${rowDelta}B`; // Move down\n\t\t} else if (rowDelta < 0) {\n\t\t\tbuffer += `\\x1b[${-rowDelta}A`; // Move up\n\t\t}\n\t\t// Move to absolute column (1-indexed)\n\t\tbuffer += `\\x1b[${targetCol + 1}G`;\n\n\t\tif (buffer) {\n\t\t\tthis.terminal.write(buffer);\n\t\t}\n\n\t\tthis.hardwareCursorRow = targetRow;\n\t\tif (this.showHardwareCursor) {\n\t\t\tthis.terminal.showCursor();\n\t\t} else {\n\t\t\tthis.terminal.hideCursor();\n\t\t}\n\t}\n}\n"]}
|