@apholdings/jensen-tui 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +767 -0
  2. package/dist/autocomplete.d.ts +50 -0
  3. package/dist/autocomplete.d.ts.map +1 -0
  4. package/dist/autocomplete.js +596 -0
  5. package/dist/autocomplete.js.map +1 -0
  6. package/dist/components/box.d.ts +22 -0
  7. package/dist/components/box.d.ts.map +1 -0
  8. package/dist/components/box.js +104 -0
  9. package/dist/components/box.js.map +1 -0
  10. package/dist/components/cancellable-loader.d.ts +22 -0
  11. package/dist/components/cancellable-loader.d.ts.map +1 -0
  12. package/dist/components/cancellable-loader.js +35 -0
  13. package/dist/components/cancellable-loader.js.map +1 -0
  14. package/dist/components/editor.d.ts +237 -0
  15. package/dist/components/editor.d.ts.map +1 -0
  16. package/dist/components/editor.js +1843 -0
  17. package/dist/components/editor.js.map +1 -0
  18. package/dist/components/image.d.ts +28 -0
  19. package/dist/components/image.d.ts.map +1 -0
  20. package/dist/components/image.js +69 -0
  21. package/dist/components/image.js.map +1 -0
  22. package/dist/components/input.d.ts +37 -0
  23. package/dist/components/input.d.ts.map +1 -0
  24. package/dist/components/input.js +426 -0
  25. package/dist/components/input.js.map +1 -0
  26. package/dist/components/loader.d.ts +21 -0
  27. package/dist/components/loader.d.ts.map +1 -0
  28. package/dist/components/loader.js +49 -0
  29. package/dist/components/loader.js.map +1 -0
  30. package/dist/components/markdown.d.ts +95 -0
  31. package/dist/components/markdown.d.ts.map +1 -0
  32. package/dist/components/markdown.js +651 -0
  33. package/dist/components/markdown.js.map +1 -0
  34. package/dist/components/select-list.d.ts +32 -0
  35. package/dist/components/select-list.d.ts.map +1 -0
  36. package/dist/components/select-list.js +152 -0
  37. package/dist/components/select-list.js.map +1 -0
  38. package/dist/components/settings-list.d.ts +50 -0
  39. package/dist/components/settings-list.d.ts.map +1 -0
  40. package/dist/components/settings-list.js +185 -0
  41. package/dist/components/settings-list.js.map +1 -0
  42. package/dist/components/spacer.d.ts +12 -0
  43. package/dist/components/spacer.d.ts.map +1 -0
  44. package/dist/components/spacer.js +23 -0
  45. package/dist/components/spacer.js.map +1 -0
  46. package/dist/components/text.d.ts +19 -0
  47. package/dist/components/text.d.ts.map +1 -0
  48. package/dist/components/text.js +89 -0
  49. package/dist/components/text.js.map +1 -0
  50. package/dist/components/truncated-text.d.ts +13 -0
  51. package/dist/components/truncated-text.d.ts.map +1 -0
  52. package/dist/components/truncated-text.js +51 -0
  53. package/dist/components/truncated-text.js.map +1 -0
  54. package/dist/editor-component.d.ts +39 -0
  55. package/dist/editor-component.d.ts.map +1 -0
  56. package/dist/editor-component.js +2 -0
  57. package/dist/editor-component.js.map +1 -0
  58. package/dist/fuzzy.d.ts +16 -0
  59. package/dist/fuzzy.d.ts.map +1 -0
  60. package/dist/fuzzy.js +107 -0
  61. package/dist/fuzzy.js.map +1 -0
  62. package/dist/index.d.ts +23 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +32 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/keybindings.d.ts +39 -0
  67. package/dist/keybindings.d.ts.map +1 -0
  68. package/dist/keybindings.js +117 -0
  69. package/dist/keybindings.js.map +1 -0
  70. package/dist/keys.d.ts +170 -0
  71. package/dist/keys.d.ts.map +1 -0
  72. package/dist/keys.js +1046 -0
  73. package/dist/keys.js.map +1 -0
  74. package/dist/kill-ring.d.ts +28 -0
  75. package/dist/kill-ring.d.ts.map +1 -0
  76. package/dist/kill-ring.js +44 -0
  77. package/dist/kill-ring.js.map +1 -0
  78. package/dist/stdin-buffer.d.ts +48 -0
  79. package/dist/stdin-buffer.d.ts.map +1 -0
  80. package/dist/stdin-buffer.js +317 -0
  81. package/dist/stdin-buffer.js.map +1 -0
  82. package/dist/terminal-image.d.ts +68 -0
  83. package/dist/terminal-image.d.ts.map +1 -0
  84. package/dist/terminal-image.js +288 -0
  85. package/dist/terminal-image.js.map +1 -0
  86. package/dist/terminal.d.ts +84 -0
  87. package/dist/terminal.d.ts.map +1 -0
  88. package/dist/terminal.js +273 -0
  89. package/dist/terminal.js.map +1 -0
  90. package/dist/tui.d.ts +229 -0
  91. package/dist/tui.d.ts.map +1 -0
  92. package/dist/tui.js +1025 -0
  93. package/dist/tui.js.map +1 -0
  94. package/dist/undo-stack.d.ts +17 -0
  95. package/dist/undo-stack.d.ts.map +1 -0
  96. package/dist/undo-stack.js +25 -0
  97. package/dist/undo-stack.js.map +1 -0
  98. package/dist/utils.d.ts +78 -0
  99. package/dist/utils.d.ts.map +1 -0
  100. package/dist/utils.js +815 -0
  101. package/dist/utils.js.map +1 -0
  102. package/package.json +59 -0
package/dist/tui.js ADDED
@@ -0,0 +1,1025 @@
1
+ /**
2
+ * Minimal TUI implementation with differential rendering
3
+ */
4
+ import * as fs from "node:fs";
5
+ import * as os from "node:os";
6
+ import * as path from "node:path";
7
+ import { isKeyRelease, matchesKey } from "./keys.js";
8
+ import { getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.js";
9
+ import { extractSegments, sliceByColumn, sliceWithWidth, visibleWidth } from "./utils.js";
10
+ /** Type guard to check if a component implements Focusable */
11
+ export function isFocusable(component) {
12
+ return component !== null && "focused" in component;
13
+ }
14
+ /**
15
+ * Cursor position marker - APC (Application Program Command) sequence.
16
+ * This is a zero-width escape sequence that terminals ignore.
17
+ * Components emit this at the cursor position when focused.
18
+ * TUI finds and strips this marker, then positions the hardware cursor there.
19
+ */
20
+ export const CURSOR_MARKER = "\x1b_pi:c\x07";
21
+ export { visibleWidth };
22
+ /** Parse a SizeValue into absolute value given a reference size */
23
+ function parseSizeValue(value, referenceSize) {
24
+ if (value === undefined)
25
+ return undefined;
26
+ if (typeof value === "number")
27
+ return value;
28
+ // Parse percentage string like "50%"
29
+ const match = value.match(/^(\d+(?:\.\d+)?)%$/);
30
+ if (match) {
31
+ return Math.floor((referenceSize * parseFloat(match[1])) / 100);
32
+ }
33
+ return undefined;
34
+ }
35
+ /**
36
+ * Container - a component that contains other components
37
+ */
38
+ export class Container {
39
+ children = [];
40
+ addChild(component) {
41
+ this.children.push(component);
42
+ }
43
+ removeChild(component) {
44
+ const index = this.children.indexOf(component);
45
+ if (index !== -1) {
46
+ this.children.splice(index, 1);
47
+ }
48
+ }
49
+ clear() {
50
+ this.children = [];
51
+ }
52
+ invalidate() {
53
+ for (const child of this.children) {
54
+ child.invalidate?.();
55
+ }
56
+ }
57
+ render(width) {
58
+ const lines = [];
59
+ for (const child of this.children) {
60
+ lines.push(...child.render(width));
61
+ }
62
+ return lines;
63
+ }
64
+ }
65
+ /**
66
+ * TUI - Main class for managing terminal UI with differential rendering
67
+ */
68
+ export class TUI extends Container {
69
+ terminal;
70
+ previousLines = [];
71
+ previousWidth = 0;
72
+ previousHeight = 0;
73
+ focusedComponent = null;
74
+ windowFocused = true;
75
+ inputListeners = new Set();
76
+ windowFocusListeners = new Set();
77
+ focusTargetListeners = new Set();
78
+ /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
79
+ onDebug;
80
+ renderRequested = false;
81
+ cursorRow = 0; // Logical cursor row (end of rendered content)
82
+ hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)
83
+ inputBuffer = ""; // Buffer for parsing terminal responses
84
+ cellSizeQueryPending = false;
85
+ showHardwareCursor = process.env.PI_HARDWARE_CURSOR === "1";
86
+ clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === "1"; // Clear empty rows when content shrinks (default: off)
87
+ maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)
88
+ previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves
89
+ fullRedrawCount = 0;
90
+ stopped = false;
91
+ // Overlay stack for modal components rendered on top of base content
92
+ focusOrderCounter = 0;
93
+ overlayStack = [];
94
+ constructor(terminal, showHardwareCursor) {
95
+ super();
96
+ this.terminal = terminal;
97
+ if (showHardwareCursor !== undefined) {
98
+ this.showHardwareCursor = showHardwareCursor;
99
+ }
100
+ }
101
+ get fullRedraws() {
102
+ return this.fullRedrawCount;
103
+ }
104
+ getShowHardwareCursor() {
105
+ return this.showHardwareCursor;
106
+ }
107
+ setShowHardwareCursor(enabled) {
108
+ if (this.showHardwareCursor === enabled)
109
+ return;
110
+ this.showHardwareCursor = enabled;
111
+ if (!enabled) {
112
+ this.terminal.hideCursor();
113
+ }
114
+ this.requestRender();
115
+ }
116
+ getClearOnShrink() {
117
+ return this.clearOnShrink;
118
+ }
119
+ /**
120
+ * Set whether to trigger full re-render when content shrinks.
121
+ * When true (default), empty rows are cleared when content shrinks.
122
+ * When false, empty rows remain (reduces redraws on slower terminals).
123
+ */
124
+ setClearOnShrink(enabled) {
125
+ this.clearOnShrink = enabled;
126
+ }
127
+ setFocus(component) {
128
+ if (this.focusedComponent === component) {
129
+ return;
130
+ }
131
+ // Clear focused flag on old component
132
+ if (isFocusable(this.focusedComponent)) {
133
+ this.focusedComponent.focused = false;
134
+ }
135
+ this.focusedComponent = component;
136
+ // Set focused flag on new component
137
+ if (isFocusable(component)) {
138
+ component.focused = true;
139
+ }
140
+ for (const listener of this.focusTargetListeners) {
141
+ listener(this.focusedComponent);
142
+ }
143
+ }
144
+ getFocusedComponent() {
145
+ return this.focusedComponent;
146
+ }
147
+ isWindowFocused() {
148
+ return this.windowFocused;
149
+ }
150
+ onWindowFocusChange(listener) {
151
+ this.windowFocusListeners.add(listener);
152
+ return () => {
153
+ this.windowFocusListeners.delete(listener);
154
+ };
155
+ }
156
+ onFocusTargetChange(listener) {
157
+ this.focusTargetListeners.add(listener);
158
+ return () => {
159
+ this.focusTargetListeners.delete(listener);
160
+ };
161
+ }
162
+ /**
163
+ * Show an overlay component with configurable positioning and sizing.
164
+ * Returns a handle to control the overlay's visibility.
165
+ */
166
+ showOverlay(component, options) {
167
+ const entry = {
168
+ component,
169
+ options,
170
+ preFocus: this.focusedComponent,
171
+ hidden: false,
172
+ focusOrder: ++this.focusOrderCounter,
173
+ };
174
+ this.overlayStack.push(entry);
175
+ // Only focus if overlay is actually visible
176
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
177
+ this.setFocus(component);
178
+ }
179
+ this.terminal.hideCursor();
180
+ this.requestRender();
181
+ // Return handle for controlling this overlay
182
+ return {
183
+ hide: () => {
184
+ const index = this.overlayStack.indexOf(entry);
185
+ if (index !== -1) {
186
+ this.overlayStack.splice(index, 1);
187
+ // Restore focus if this overlay had focus
188
+ if (this.focusedComponent === component) {
189
+ const topVisible = this.getTopmostVisibleOverlay();
190
+ this.setFocus(topVisible?.component ?? entry.preFocus);
191
+ }
192
+ if (this.overlayStack.length === 0)
193
+ this.terminal.hideCursor();
194
+ this.requestRender();
195
+ }
196
+ },
197
+ setHidden: (hidden) => {
198
+ if (entry.hidden === hidden)
199
+ return;
200
+ entry.hidden = hidden;
201
+ // Update focus when hiding/showing
202
+ if (hidden) {
203
+ // If this overlay had focus, move focus to next visible or preFocus
204
+ if (this.focusedComponent === component) {
205
+ const topVisible = this.getTopmostVisibleOverlay();
206
+ this.setFocus(topVisible?.component ?? entry.preFocus);
207
+ }
208
+ }
209
+ else {
210
+ // Restore focus to this overlay when showing (if it's actually visible)
211
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
212
+ entry.focusOrder = ++this.focusOrderCounter;
213
+ this.setFocus(component);
214
+ }
215
+ }
216
+ this.requestRender();
217
+ },
218
+ isHidden: () => entry.hidden,
219
+ focus: () => {
220
+ if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry))
221
+ return;
222
+ if (this.focusedComponent !== component) {
223
+ this.setFocus(component);
224
+ }
225
+ entry.focusOrder = ++this.focusOrderCounter;
226
+ this.requestRender();
227
+ },
228
+ unfocus: () => {
229
+ if (this.focusedComponent !== component)
230
+ return;
231
+ const topVisible = this.getTopmostVisibleOverlay();
232
+ this.setFocus(topVisible && topVisible !== entry ? topVisible.component : entry.preFocus);
233
+ this.requestRender();
234
+ },
235
+ isFocused: () => this.focusedComponent === component,
236
+ };
237
+ }
238
+ /** Hide the topmost overlay and restore previous focus. */
239
+ hideOverlay() {
240
+ const overlay = this.overlayStack.pop();
241
+ if (!overlay)
242
+ return;
243
+ if (this.focusedComponent === overlay.component) {
244
+ // Find topmost visible overlay, or fall back to preFocus
245
+ const topVisible = this.getTopmostVisibleOverlay();
246
+ this.setFocus(topVisible?.component ?? overlay.preFocus);
247
+ }
248
+ if (this.overlayStack.length === 0)
249
+ this.terminal.hideCursor();
250
+ this.requestRender();
251
+ }
252
+ /** Check if there are any visible overlays */
253
+ hasOverlay() {
254
+ return this.overlayStack.some((o) => this.isOverlayVisible(o));
255
+ }
256
+ /** Check if an overlay entry is currently visible */
257
+ isOverlayVisible(entry) {
258
+ if (entry.hidden)
259
+ return false;
260
+ if (entry.options?.visible) {
261
+ return entry.options.visible(this.terminal.columns, this.terminal.rows);
262
+ }
263
+ return true;
264
+ }
265
+ /** Find the topmost visible capturing overlay, if any */
266
+ getTopmostVisibleOverlay() {
267
+ for (let i = this.overlayStack.length - 1; i >= 0; i--) {
268
+ if (this.overlayStack[i].options?.nonCapturing)
269
+ continue;
270
+ if (this.isOverlayVisible(this.overlayStack[i])) {
271
+ return this.overlayStack[i];
272
+ }
273
+ }
274
+ return undefined;
275
+ }
276
+ invalidate() {
277
+ super.invalidate();
278
+ for (const overlay of this.overlayStack)
279
+ overlay.component.invalidate?.();
280
+ }
281
+ start() {
282
+ this.stopped = false;
283
+ this.terminal.start((data) => this.handleInput(data), () => this.requestRender());
284
+ this.terminal.hideCursor();
285
+ this.queryCellSize();
286
+ this.requestRender();
287
+ }
288
+ addInputListener(listener) {
289
+ this.inputListeners.add(listener);
290
+ return () => {
291
+ this.inputListeners.delete(listener);
292
+ };
293
+ }
294
+ removeInputListener(listener) {
295
+ this.inputListeners.delete(listener);
296
+ }
297
+ queryCellSize() {
298
+ // Only query if terminal supports images (cell size is only used for image rendering)
299
+ if (!getCapabilities().images) {
300
+ return;
301
+ }
302
+ // Query terminal for cell size in pixels: CSI 16 t
303
+ // Response format: CSI 6 ; height ; width t
304
+ this.cellSizeQueryPending = true;
305
+ this.terminal.write("\x1b[16t");
306
+ }
307
+ stop() {
308
+ this.stopped = true;
309
+ // Move cursor to the end of the content to prevent overwriting/artifacts on exit
310
+ if (this.previousLines.length > 0) {
311
+ const targetRow = this.previousLines.length; // Line after the last content
312
+ const lineDiff = targetRow - this.hardwareCursorRow;
313
+ if (lineDiff > 0) {
314
+ this.terminal.write(`\x1b[${lineDiff}B`);
315
+ }
316
+ else if (lineDiff < 0) {
317
+ this.terminal.write(`\x1b[${-lineDiff}A`);
318
+ }
319
+ this.terminal.write("\r\n");
320
+ }
321
+ this.terminal.showCursor();
322
+ this.terminal.stop();
323
+ }
324
+ requestRender(force = false) {
325
+ if (force) {
326
+ this.previousLines = [];
327
+ this.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear
328
+ this.previousHeight = -1; // -1 triggers heightChanged, forcing a full clear
329
+ this.cursorRow = 0;
330
+ this.hardwareCursorRow = 0;
331
+ this.maxLinesRendered = 0;
332
+ this.previousViewportTop = 0;
333
+ }
334
+ if (this.renderRequested)
335
+ return;
336
+ this.renderRequested = true;
337
+ process.nextTick(() => {
338
+ this.renderRequested = false;
339
+ this.doRender();
340
+ });
341
+ }
342
+ handleInput(data) {
343
+ if (this.inputListeners.size > 0) {
344
+ let current = data;
345
+ for (const listener of this.inputListeners) {
346
+ const result = listener(current);
347
+ if (result?.consume) {
348
+ return;
349
+ }
350
+ if (result?.data !== undefined) {
351
+ current = result.data;
352
+ }
353
+ }
354
+ if (current.length === 0) {
355
+ return;
356
+ }
357
+ data = current;
358
+ }
359
+ if (data === "\x1b[I") {
360
+ if (!this.windowFocused) {
361
+ this.windowFocused = true;
362
+ for (const listener of this.windowFocusListeners) {
363
+ listener(true);
364
+ }
365
+ this.requestRender();
366
+ }
367
+ return;
368
+ }
369
+ if (data === "\x1b[O") {
370
+ if (this.windowFocused) {
371
+ this.windowFocused = false;
372
+ for (const listener of this.windowFocusListeners) {
373
+ listener(false);
374
+ }
375
+ this.requestRender();
376
+ }
377
+ return;
378
+ }
379
+ // If we're waiting for cell size response, buffer input and parse
380
+ if (this.cellSizeQueryPending) {
381
+ this.inputBuffer += data;
382
+ const filtered = this.parseCellSizeResponse();
383
+ if (filtered.length === 0)
384
+ return;
385
+ data = filtered;
386
+ }
387
+ // Global debug key handler (Shift+Ctrl+D)
388
+ if (matchesKey(data, "shift+ctrl+d") && this.onDebug) {
389
+ this.onDebug();
390
+ return;
391
+ }
392
+ // If focused component is an overlay, verify it's still visible
393
+ // (visibility can change due to terminal resize or visible() callback)
394
+ const focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);
395
+ if (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {
396
+ // Focused overlay is no longer visible, redirect to topmost visible overlay
397
+ const topVisible = this.getTopmostVisibleOverlay();
398
+ if (topVisible) {
399
+ this.setFocus(topVisible.component);
400
+ }
401
+ else {
402
+ // No visible overlays, restore to preFocus
403
+ this.setFocus(focusedOverlay.preFocus);
404
+ }
405
+ }
406
+ // Pass input to focused component (including Ctrl+C)
407
+ // The focused component can decide how to handle Ctrl+C
408
+ if (this.focusedComponent?.handleInput) {
409
+ // Filter out key release events unless component opts in
410
+ if (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {
411
+ return;
412
+ }
413
+ this.focusedComponent.handleInput(data);
414
+ this.requestRender();
415
+ }
416
+ }
417
+ parseCellSizeResponse() {
418
+ // Response format: ESC [ 6 ; height ; width t
419
+ // Match the response pattern
420
+ const responsePattern = /\x1b\[6;(\d+);(\d+)t/;
421
+ const match = this.inputBuffer.match(responsePattern);
422
+ if (match) {
423
+ const heightPx = parseInt(match[1], 10);
424
+ const widthPx = parseInt(match[2], 10);
425
+ if (heightPx > 0 && widthPx > 0) {
426
+ setCellDimensions({ widthPx, heightPx });
427
+ // Invalidate all components so images re-render with correct dimensions
428
+ this.invalidate();
429
+ this.requestRender();
430
+ }
431
+ // Remove the response from buffer
432
+ this.inputBuffer = this.inputBuffer.replace(responsePattern, "");
433
+ this.cellSizeQueryPending = false;
434
+ }
435
+ // Check if we have a partial cell size response starting (wait for more data)
436
+ // Patterns that could be incomplete cell size response: \x1b, \x1b[, \x1b[6, \x1b[6;...(no t yet)
437
+ const partialCellSizePattern = /\x1b(\[6?;?[\d;]*)?$/;
438
+ if (partialCellSizePattern.test(this.inputBuffer)) {
439
+ // Check if it's actually a complete different escape sequence (ends with a letter)
440
+ // Cell size response ends with 't', Kitty keyboard ends with 'u', arrows end with A-D, etc.
441
+ const lastChar = this.inputBuffer[this.inputBuffer.length - 1];
442
+ if (!/[a-zA-Z~]/.test(lastChar)) {
443
+ // Doesn't end with a terminator, might be incomplete - wait for more
444
+ return "";
445
+ }
446
+ }
447
+ // No cell size response found, return buffered data as user input
448
+ const result = this.inputBuffer;
449
+ this.inputBuffer = "";
450
+ this.cellSizeQueryPending = false; // Give up waiting
451
+ return result;
452
+ }
453
+ /**
454
+ * Resolve overlay layout from options.
455
+ * Returns { width, row, col, maxHeight } for rendering.
456
+ */
457
+ resolveOverlayLayout(options, overlayHeight, termWidth, termHeight) {
458
+ const opt = options ?? {};
459
+ // Parse margin (clamp to non-negative)
460
+ const margin = typeof opt.margin === "number"
461
+ ? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }
462
+ : (opt.margin ?? {});
463
+ const marginTop = Math.max(0, margin.top ?? 0);
464
+ const marginRight = Math.max(0, margin.right ?? 0);
465
+ const marginBottom = Math.max(0, margin.bottom ?? 0);
466
+ const marginLeft = Math.max(0, margin.left ?? 0);
467
+ // Available space after margins
468
+ const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
469
+ const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
470
+ // === Resolve width ===
471
+ let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
472
+ // Apply minWidth
473
+ if (opt.minWidth !== undefined) {
474
+ width = Math.max(width, opt.minWidth);
475
+ }
476
+ // Clamp to available space
477
+ width = Math.max(1, Math.min(width, availWidth));
478
+ // === Resolve maxHeight ===
479
+ let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
480
+ // Clamp to available space
481
+ if (maxHeight !== undefined) {
482
+ maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
483
+ }
484
+ // Effective overlay height (may be clamped by maxHeight)
485
+ const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
486
+ // === Resolve position ===
487
+ let row;
488
+ let col;
489
+ if (opt.row !== undefined) {
490
+ if (typeof opt.row === "string") {
491
+ // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
492
+ const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
493
+ if (match) {
494
+ const maxRow = Math.max(0, availHeight - effectiveHeight);
495
+ const percent = parseFloat(match[1]) / 100;
496
+ row = marginTop + Math.floor(maxRow * percent);
497
+ }
498
+ else {
499
+ // Invalid format, fall back to center
500
+ row = this.resolveAnchorRow("center", effectiveHeight, availHeight, marginTop);
501
+ }
502
+ }
503
+ else {
504
+ // Absolute row position
505
+ row = opt.row;
506
+ }
507
+ }
508
+ else {
509
+ // Anchor-based (default: center)
510
+ const anchor = opt.anchor ?? "center";
511
+ row = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
512
+ }
513
+ if (opt.col !== undefined) {
514
+ if (typeof opt.col === "string") {
515
+ // Percentage: 0% = left, 100% = right (overlay stays within bounds)
516
+ const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
517
+ if (match) {
518
+ const maxCol = Math.max(0, availWidth - width);
519
+ const percent = parseFloat(match[1]) / 100;
520
+ col = marginLeft + Math.floor(maxCol * percent);
521
+ }
522
+ else {
523
+ // Invalid format, fall back to center
524
+ col = this.resolveAnchorCol("center", width, availWidth, marginLeft);
525
+ }
526
+ }
527
+ else {
528
+ // Absolute column position
529
+ col = opt.col;
530
+ }
531
+ }
532
+ else {
533
+ // Anchor-based (default: center)
534
+ const anchor = opt.anchor ?? "center";
535
+ col = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);
536
+ }
537
+ // Apply offsets
538
+ if (opt.offsetY !== undefined)
539
+ row += opt.offsetY;
540
+ if (opt.offsetX !== undefined)
541
+ col += opt.offsetX;
542
+ // Clamp to terminal bounds (respecting margins)
543
+ row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
544
+ col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
545
+ return { width, row, col, maxHeight };
546
+ }
547
+ resolveAnchorRow(anchor, height, availHeight, marginTop) {
548
+ switch (anchor) {
549
+ case "top-left":
550
+ case "top-center":
551
+ case "top-right":
552
+ return marginTop;
553
+ case "bottom-left":
554
+ case "bottom-center":
555
+ case "bottom-right":
556
+ return marginTop + availHeight - height;
557
+ case "left-center":
558
+ case "center":
559
+ case "right-center":
560
+ return marginTop + Math.floor((availHeight - height) / 2);
561
+ }
562
+ }
563
+ resolveAnchorCol(anchor, width, availWidth, marginLeft) {
564
+ switch (anchor) {
565
+ case "top-left":
566
+ case "left-center":
567
+ case "bottom-left":
568
+ return marginLeft;
569
+ case "top-right":
570
+ case "right-center":
571
+ case "bottom-right":
572
+ return marginLeft + availWidth - width;
573
+ case "top-center":
574
+ case "center":
575
+ case "bottom-center":
576
+ return marginLeft + Math.floor((availWidth - width) / 2);
577
+ }
578
+ }
579
+ /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
580
+ compositeOverlays(lines, termWidth, termHeight) {
581
+ if (this.overlayStack.length === 0)
582
+ return lines;
583
+ const result = [...lines];
584
+ // Pre-render all visible overlays and calculate positions
585
+ const rendered = [];
586
+ let minLinesNeeded = result.length;
587
+ const visibleEntries = this.overlayStack.filter((e) => this.isOverlayVisible(e));
588
+ visibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);
589
+ for (const entry of visibleEntries) {
590
+ const { component, options } = entry;
591
+ // Get layout with height=0 first to determine width and maxHeight
592
+ // (width and maxHeight don't depend on overlay height)
593
+ const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
594
+ // Render component at calculated width
595
+ let overlayLines = component.render(width);
596
+ // Apply maxHeight if specified
597
+ if (maxHeight !== undefined && overlayLines.length > maxHeight) {
598
+ overlayLines = overlayLines.slice(0, maxHeight);
599
+ }
600
+ // Get final row/col with actual overlay height
601
+ const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
602
+ rendered.push({ overlayLines, row, col, w: width });
603
+ minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
604
+ }
605
+ // Only preserve the historical working area while the current composed frame still overflows.
606
+ // Once everything fits again, reset overlay anchoring to the real top of the viewport.
607
+ const workingHeight = minLinesNeeded <= termHeight ? minLinesNeeded : Math.max(this.maxLinesRendered, minLinesNeeded);
608
+ // Extend result with empty lines if content is too short for overlay placement or working area
609
+ while (result.length < workingHeight) {
610
+ result.push("");
611
+ }
612
+ const viewportStart = Math.max(0, workingHeight - termHeight);
613
+ // Composite each overlay
614
+ for (const { overlayLines, row, col, w } of rendered) {
615
+ for (let i = 0; i < overlayLines.length; i++) {
616
+ const idx = viewportStart + row + i;
617
+ if (idx >= 0 && idx < result.length) {
618
+ // Defensive: truncate overlay line to declared width before compositing
619
+ // (components should already respect width, but this ensures it)
620
+ const truncatedOverlayLine = visibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];
621
+ result[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
622
+ }
623
+ }
624
+ }
625
+ return result;
626
+ }
627
+ static SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07";
628
+ applyLineResets(lines) {
629
+ const reset = TUI.SEGMENT_RESET;
630
+ for (let i = 0; i < lines.length; i++) {
631
+ const line = lines[i];
632
+ if (!isImageLine(line)) {
633
+ lines[i] = line + reset;
634
+ }
635
+ }
636
+ return lines;
637
+ }
638
+ /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
639
+ compositeLineAt(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
640
+ if (isImageLine(baseLine))
641
+ return baseLine;
642
+ // Single pass through baseLine extracts both before and after segments
643
+ const afterStart = startCol + overlayWidth;
644
+ const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
645
+ // Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
646
+ const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
647
+ // Pad segments to target widths
648
+ const beforePad = Math.max(0, startCol - base.beforeWidth);
649
+ const overlayPad = Math.max(0, overlayWidth - overlay.width);
650
+ const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
651
+ const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
652
+ const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
653
+ const afterPad = Math.max(0, afterTarget - base.afterWidth);
654
+ // Compose result
655
+ const r = TUI.SEGMENT_RESET;
656
+ const result = base.before +
657
+ " ".repeat(beforePad) +
658
+ r +
659
+ overlay.text +
660
+ " ".repeat(overlayPad) +
661
+ r +
662
+ base.after +
663
+ " ".repeat(afterPad);
664
+ // CRITICAL: Always verify and truncate to terminal width.
665
+ // This is the final safeguard against width overflow which would crash the TUI.
666
+ // Width tracking can drift from actual visible width due to:
667
+ // - Complex ANSI/OSC sequences (hyperlinks, colors)
668
+ // - Wide characters at segment boundaries
669
+ // - Edge cases in segment extraction
670
+ const resultWidth = visibleWidth(result);
671
+ if (resultWidth <= totalWidth) {
672
+ return result;
673
+ }
674
+ // Truncate with strict=true to ensure we don't exceed totalWidth
675
+ return sliceByColumn(result, 0, totalWidth, true);
676
+ }
677
+ /**
678
+ * Find and extract cursor position from rendered lines.
679
+ * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
680
+ * Only scans the bottom terminal height lines (visible viewport).
681
+ * @param lines - Rendered lines to search
682
+ * @param height - Terminal height (visible viewport size)
683
+ * @returns Cursor position { row, col } or null if no marker found
684
+ */
685
+ extractCursorPosition(lines, height) {
686
+ // Only scan the bottom `height` lines (visible viewport)
687
+ const viewportTop = Math.max(0, lines.length - height);
688
+ for (let row = lines.length - 1; row >= viewportTop; row--) {
689
+ const line = lines[row];
690
+ const markerIndex = line.indexOf(CURSOR_MARKER);
691
+ if (markerIndex !== -1) {
692
+ // Calculate visual column (width of text before marker)
693
+ const beforeMarker = line.slice(0, markerIndex);
694
+ const col = visibleWidth(beforeMarker);
695
+ // Strip marker from the line
696
+ lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
697
+ return { row, col };
698
+ }
699
+ }
700
+ return null;
701
+ }
702
+ doRender() {
703
+ if (this.stopped)
704
+ return;
705
+ const width = this.terminal.columns;
706
+ const height = this.terminal.rows;
707
+ // Render all components to get new lines
708
+ let newLines = this.render(width);
709
+ // Composite overlays into the rendered lines (before differential compare)
710
+ if (this.overlayStack.length > 0) {
711
+ newLines = this.compositeOverlays(newLines, width, height);
712
+ }
713
+ // Extract cursor position before applying line resets (marker must be found first)
714
+ const cursorPos = this.extractCursorPosition(newLines, height);
715
+ newLines = this.applyLineResets(newLines);
716
+ const frameFits = newLines.length <= height;
717
+ let viewportTop = frameFits ? 0 : Math.max(0, this.maxLinesRendered - height);
718
+ let prevViewportTop = this.previousLines.length <= height ? 0 : this.previousViewportTop;
719
+ let hardwareCursorRow = this.hardwareCursorRow;
720
+ const computeLineDiff = (targetRow) => {
721
+ const currentScreenRow = hardwareCursorRow - prevViewportTop;
722
+ const targetScreenRow = targetRow - viewportTop;
723
+ return targetScreenRow - currentScreenRow;
724
+ };
725
+ // Width or height changed - need full re-render
726
+ const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
727
+ const heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;
728
+ // Helper to clear scrollback and viewport and render all new lines
729
+ const fullRender = (clear) => {
730
+ this.fullRedrawCount += 1;
731
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
732
+ if (clear)
733
+ buffer += "\x1b[3J\x1b[2J\x1b[H"; // Clear scrollback, screen, and home
734
+ for (let i = 0; i < newLines.length; i++) {
735
+ if (i > 0)
736
+ buffer += "\r\n";
737
+ buffer += newLines[i];
738
+ }
739
+ buffer += "\x1b[?2026l"; // End synchronized output
740
+ this.terminal.write(buffer);
741
+ this.cursorRow = Math.max(0, newLines.length - 1);
742
+ this.hardwareCursorRow = this.cursorRow;
743
+ // Reset max lines when clearing, otherwise track growth
744
+ if (clear) {
745
+ this.maxLinesRendered = newLines.length;
746
+ }
747
+ else {
748
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
749
+ }
750
+ this.previousViewportTop = frameFits ? 0 : Math.max(0, this.maxLinesRendered - height);
751
+ this.positionHardwareCursor(cursorPos, newLines.length);
752
+ this.previousLines = newLines;
753
+ this.previousWidth = width;
754
+ this.previousHeight = height;
755
+ };
756
+ const debugRedraw = process.env.PI_DEBUG_REDRAW === "1";
757
+ const logRedraw = (reason) => {
758
+ if (!debugRedraw)
759
+ return;
760
+ const logPath = path.join(os.homedir(), ".pi", "agent", "pi-debug.log");
761
+ const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
762
+ fs.appendFileSync(logPath, msg);
763
+ };
764
+ // First render - just output everything without clearing (assumes clean screen)
765
+ if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
766
+ logRedraw("first render");
767
+ fullRender(false);
768
+ return;
769
+ }
770
+ // Width or height changed - full re-render
771
+ if (widthChanged || heightChanged) {
772
+ logRedraw(`terminal size changed (${this.previousWidth}x${this.previousHeight} -> ${width}x${height})`);
773
+ fullRender(true);
774
+ return;
775
+ }
776
+ // Content shrunk below the working area and no overlays - re-render to clear empty rows
777
+ // (overlays need the padding, so only do this when no overlays are active)
778
+ // Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var
779
+ if (this.clearOnShrink && newLines.length < this.maxLinesRendered && this.overlayStack.length === 0) {
780
+ logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);
781
+ fullRender(true);
782
+ return;
783
+ }
784
+ // Find first and last changed lines
785
+ let firstChanged = -1;
786
+ let lastChanged = -1;
787
+ const maxLines = Math.max(newLines.length, this.previousLines.length);
788
+ for (let i = 0; i < maxLines; i++) {
789
+ const oldLine = i < this.previousLines.length ? this.previousLines[i] : "";
790
+ const newLine = i < newLines.length ? newLines[i] : "";
791
+ if (oldLine !== newLine) {
792
+ if (firstChanged === -1) {
793
+ firstChanged = i;
794
+ }
795
+ lastChanged = i;
796
+ }
797
+ }
798
+ const appendedLines = newLines.length > this.previousLines.length;
799
+ if (appendedLines) {
800
+ if (firstChanged === -1) {
801
+ firstChanged = this.previousLines.length;
802
+ }
803
+ lastChanged = newLines.length - 1;
804
+ }
805
+ const appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;
806
+ // No changes - but still need to update hardware cursor position if it moved
807
+ if (firstChanged === -1) {
808
+ this.positionHardwareCursor(cursorPos, newLines.length);
809
+ this.previousViewportTop = frameFits ? 0 : Math.max(0, this.maxLinesRendered - height);
810
+ this.previousHeight = height;
811
+ return;
812
+ }
813
+ // All changes are in deleted lines (nothing to render, just clear)
814
+ if (firstChanged >= newLines.length) {
815
+ if (this.previousLines.length > newLines.length) {
816
+ let buffer = "\x1b[?2026h";
817
+ // Move to end of new content (clamp to 0 for empty content)
818
+ const targetRow = Math.max(0, newLines.length - 1);
819
+ const lineDiff = computeLineDiff(targetRow);
820
+ if (lineDiff > 0)
821
+ buffer += `\x1b[${lineDiff}B`;
822
+ else if (lineDiff < 0)
823
+ buffer += `\x1b[${-lineDiff}A`;
824
+ buffer += "\r";
825
+ // Clear extra lines without scrolling
826
+ const extraLines = this.previousLines.length - newLines.length;
827
+ if (extraLines > height) {
828
+ logRedraw(`extraLines > height (${extraLines} > ${height})`);
829
+ fullRender(true);
830
+ return;
831
+ }
832
+ if (extraLines > 0) {
833
+ buffer += "\x1b[1B";
834
+ }
835
+ for (let i = 0; i < extraLines; i++) {
836
+ buffer += "\r\x1b[2K";
837
+ if (i < extraLines - 1)
838
+ buffer += "\x1b[1B";
839
+ }
840
+ if (extraLines > 0) {
841
+ buffer += `\x1b[${extraLines}A`;
842
+ }
843
+ buffer += "\x1b[?2026l";
844
+ this.terminal.write(buffer);
845
+ this.cursorRow = targetRow;
846
+ this.hardwareCursorRow = targetRow;
847
+ }
848
+ this.positionHardwareCursor(cursorPos, newLines.length);
849
+ this.previousLines = newLines;
850
+ this.previousWidth = width;
851
+ this.previousHeight = height;
852
+ this.previousViewportTop = frameFits ? 0 : Math.max(0, this.maxLinesRendered - height);
853
+ return;
854
+ }
855
+ // Check if firstChanged is above what was previously visible
856
+ // Use previousLines.length (not maxLinesRendered) to avoid false positives after content shrinks
857
+ const previousContentViewportTop = Math.max(0, this.previousLines.length - height);
858
+ if (firstChanged < previousContentViewportTop) {
859
+ // First change is above previous viewport - need full re-render
860
+ logRedraw(`firstChanged < viewportTop (${firstChanged} < ${previousContentViewportTop})`);
861
+ fullRender(true);
862
+ return;
863
+ }
864
+ // Render from first changed line to end
865
+ // Build buffer with all updates wrapped in synchronized output
866
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
867
+ const prevViewportBottom = prevViewportTop + height - 1;
868
+ const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
869
+ if (moveTargetRow > prevViewportBottom) {
870
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
871
+ const moveToBottom = height - 1 - currentScreenRow;
872
+ if (moveToBottom > 0) {
873
+ buffer += `\x1b[${moveToBottom}B`;
874
+ }
875
+ const scroll = moveTargetRow - prevViewportBottom;
876
+ buffer += "\r\n".repeat(scroll);
877
+ prevViewportTop += scroll;
878
+ viewportTop += scroll;
879
+ hardwareCursorRow = moveTargetRow;
880
+ }
881
+ // Move cursor to first changed line (use hardwareCursorRow for actual position)
882
+ const lineDiff = computeLineDiff(moveTargetRow);
883
+ if (lineDiff > 0) {
884
+ buffer += `\x1b[${lineDiff}B`; // Move down
885
+ }
886
+ else if (lineDiff < 0) {
887
+ buffer += `\x1b[${-lineDiff}A`; // Move up
888
+ }
889
+ buffer += appendStart ? "\r\n" : "\r"; // Move to column 0
890
+ // Only render changed lines (firstChanged to lastChanged), not all lines to end
891
+ // This reduces flicker when only a single line changes (e.g., spinner animation)
892
+ const renderEnd = Math.min(lastChanged, newLines.length - 1);
893
+ for (let i = firstChanged; i <= renderEnd; i++) {
894
+ if (i > firstChanged)
895
+ buffer += "\r\n";
896
+ buffer += "\x1b[2K"; // Clear current line
897
+ const line = newLines[i];
898
+ const isImage = isImageLine(line);
899
+ if (!isImage && visibleWidth(line) > width) {
900
+ // Log all lines to crash file for debugging
901
+ const crashLogPath = path.join(os.homedir(), ".pi", "agent", "pi-crash.log");
902
+ const crashData = [
903
+ `Crash at ${new Date().toISOString()}`,
904
+ `Terminal width: ${width}`,
905
+ `Line ${i} visible width: ${visibleWidth(line)}`,
906
+ "",
907
+ "=== All rendered lines ===",
908
+ ...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),
909
+ "",
910
+ ].join("\n");
911
+ fs.mkdirSync(path.dirname(crashLogPath), { recursive: true });
912
+ fs.writeFileSync(crashLogPath, crashData);
913
+ // Clean up terminal state before throwing
914
+ this.stop();
915
+ const errorMsg = [
916
+ `Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,
917
+ "",
918
+ "This is likely caused by a custom TUI component not truncating its output.",
919
+ "Use visibleWidth() to measure and truncateToWidth() to truncate lines.",
920
+ "",
921
+ `Debug log written to: ${crashLogPath}`,
922
+ ].join("\n");
923
+ throw new Error(errorMsg);
924
+ }
925
+ buffer += line;
926
+ }
927
+ // Track where cursor ended up after rendering
928
+ let finalCursorRow = renderEnd;
929
+ // If we had more lines before, clear them and move cursor back
930
+ if (this.previousLines.length > newLines.length) {
931
+ // Move to end of new content first if we stopped before it
932
+ if (renderEnd < newLines.length - 1) {
933
+ const moveDown = newLines.length - 1 - renderEnd;
934
+ buffer += `\x1b[${moveDown}B`;
935
+ finalCursorRow = newLines.length - 1;
936
+ }
937
+ const extraLines = this.previousLines.length - newLines.length;
938
+ for (let i = newLines.length; i < this.previousLines.length; i++) {
939
+ buffer += "\r\n\x1b[2K";
940
+ }
941
+ // Move cursor back to end of new content
942
+ buffer += `\x1b[${extraLines}A`;
943
+ }
944
+ buffer += "\x1b[?2026l"; // End synchronized output
945
+ if (process.env.PI_TUI_DEBUG === "1") {
946
+ const debugDir = "/tmp/tui";
947
+ fs.mkdirSync(debugDir, { recursive: true });
948
+ const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
949
+ const debugData = [
950
+ `firstChanged: ${firstChanged}`,
951
+ `viewportTop: ${viewportTop}`,
952
+ `cursorRow: ${this.cursorRow}`,
953
+ `height: ${height}`,
954
+ `lineDiff: ${lineDiff}`,
955
+ `hardwareCursorRow: ${hardwareCursorRow}`,
956
+ `renderEnd: ${renderEnd}`,
957
+ `finalCursorRow: ${finalCursorRow}`,
958
+ `cursorPos: ${JSON.stringify(cursorPos)}`,
959
+ `newLines.length: ${newLines.length}`,
960
+ `previousLines.length: ${this.previousLines.length}`,
961
+ "",
962
+ "=== newLines ===",
963
+ JSON.stringify(newLines, null, 2),
964
+ "",
965
+ "=== previousLines ===",
966
+ JSON.stringify(this.previousLines, null, 2),
967
+ "",
968
+ "=== buffer ===",
969
+ JSON.stringify(buffer),
970
+ ].join("\n");
971
+ fs.writeFileSync(debugPath, debugData);
972
+ }
973
+ // Write entire buffer at once
974
+ this.terminal.write(buffer);
975
+ // Track cursor position for next render
976
+ // cursorRow tracks end of content (for viewport calculation)
977
+ // hardwareCursorRow tracks actual terminal cursor position (for movement)
978
+ this.cursorRow = Math.max(0, newLines.length - 1);
979
+ this.hardwareCursorRow = finalCursorRow;
980
+ // Track terminal's working area (grows but doesn't shrink unless cleared)
981
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
982
+ this.previousViewportTop = frameFits ? 0 : Math.max(0, this.maxLinesRendered - height);
983
+ // Position hardware cursor for IME
984
+ this.positionHardwareCursor(cursorPos, newLines.length);
985
+ this.previousLines = newLines;
986
+ this.previousWidth = width;
987
+ this.previousHeight = height;
988
+ }
989
+ /**
990
+ * Position the hardware cursor for IME candidate window.
991
+ * @param cursorPos The cursor position extracted from rendered output, or null
992
+ * @param totalLines Total number of rendered lines
993
+ */
994
+ positionHardwareCursor(cursorPos, totalLines) {
995
+ if (!cursorPos || totalLines <= 0) {
996
+ this.terminal.hideCursor();
997
+ return;
998
+ }
999
+ // Clamp cursor position to valid range
1000
+ const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
1001
+ const targetCol = Math.max(0, cursorPos.col);
1002
+ // Move cursor from current position to target
1003
+ const rowDelta = targetRow - this.hardwareCursorRow;
1004
+ let buffer = "";
1005
+ if (rowDelta > 0) {
1006
+ buffer += `\x1b[${rowDelta}B`; // Move down
1007
+ }
1008
+ else if (rowDelta < 0) {
1009
+ buffer += `\x1b[${-rowDelta}A`; // Move up
1010
+ }
1011
+ // Move to absolute column (1-indexed)
1012
+ buffer += `\x1b[${targetCol + 1}G`;
1013
+ if (buffer) {
1014
+ this.terminal.write(buffer);
1015
+ }
1016
+ this.hardwareCursorRow = targetRow;
1017
+ if (this.showHardwareCursor) {
1018
+ this.terminal.showCursor();
1019
+ }
1020
+ else {
1021
+ this.terminal.hideCursor();
1022
+ }
1023
+ }
1024
+ }
1025
+ //# sourceMappingURL=tui.js.map