@dreb/tui 1.16.0

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