@kolisachint/hoocode-tui 0.5.67 → 0.5.69

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/dist/tui.js CHANGED
@@ -5,9 +5,11 @@ import * as fs from "node:fs";
5
5
  import * as os from "node:os";
6
6
  import * as path from "node:path";
7
7
  import { performance } from "node:perf_hooks";
8
+ import { stripVTControlCharacters } from "node:util";
8
9
  import { isKeyRelease, matchesKey } from "./keys.js";
10
+ import { mouseSequenceLength, parseMouseEvent } from "./mouse.js";
9
11
  import { deleteKittyImage, getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.js";
10
- import { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, visibleWidth } from "./utils.js";
12
+ import { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, truncateToWidth, visibleWidth, } from "./utils.js";
11
13
  const KITTY_SEQUENCE_PREFIX = "\x1b_G";
12
14
  function extractKittyImageIds(line) {
13
15
  const sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);
@@ -47,6 +49,35 @@ export const CURSOR_MARKER = "\x1b_pi:c\x07";
47
49
  */
48
50
  const HIDE_CURSOR = "\x1b[?25l";
49
51
  const SHOW_CURSOR = "\x1b[?25h";
52
+ /**
53
+ * How far one wheel notch moves the pinned view.
54
+ *
55
+ * Three lines is what terminals, pagers and browsers have settled on, and the
56
+ * agreement is the point: a wheel that moves a different distance here than in
57
+ * every other window is the kind of wrongness people feel without being able to
58
+ * name it.
59
+ */
60
+ const WHEEL_LINES = 3;
61
+ /**
62
+ * The indicator the tui draws when the app has not supplied its own.
63
+ *
64
+ * Reverse video rather than a colour, because this package has no theme and a
65
+ * hard-coded colour is the one thing guaranteed to clash with whichever one the
66
+ * app is using. It leads with the position — the question a pinned reader
67
+ * actually has — and spends what is left on the keys, dropping them on a narrow
68
+ * terminal rather than truncating the numbers.
69
+ */
70
+ function defaultScrollStatus(status) {
71
+ const position = `${status.top}–${status.bottom}/${status.total}`;
72
+ const where = status.atTop ? " top" : "";
73
+ const keys = "↑↓ line · PgUp/PgDn page · esc live";
74
+ const left = ` ${position}${where} `;
75
+ // Measured in columns, not characters: the arrows and the separator are one
76
+ // cell each but a rebind could put anything in here, and a row that is one
77
+ // cell too wide wraps into the window above it.
78
+ const body = visibleWidth(left) + visibleWidth(keys) + 1 <= status.width ? `${left}${keys} ` : left;
79
+ return `\x1b[7m${truncateToWidth(body, status.width, "", true)}\x1b[0m`;
80
+ }
50
81
  /** Parse a SizeValue into absolute value given a reference size */
51
82
  function parseSizeValue(value, referenceSize) {
52
83
  if (value === undefined)
@@ -95,6 +126,30 @@ export class Container {
95
126
  child.invalidate?.();
96
127
  }
97
128
  }
129
+ /**
130
+ * Where each direct child's output starts, in rows, from the last render.
131
+ *
132
+ * Read off the memo rather than recomputed, so asking is a walk over the
133
+ * children's cached line arrays and never a re-render. Undefined before the
134
+ * first render, or at a different width than the caller has in mind — both
135
+ * cases mean "no answer", not "zero".
136
+ *
137
+ * This is what lets something outside the tree point at a row inside it: a
138
+ * component's offset within its container, plus that container's offset at
139
+ * the root, is its absolute row in the buffer the viewport windows over.
140
+ */
141
+ childRowOffsets(width) {
142
+ const memo = this.renderMemo;
143
+ if (!memo || memo.width !== width)
144
+ return undefined;
145
+ const offsets = new Array(memo.refs.length);
146
+ let row = 0;
147
+ for (let i = 0; i < memo.refs.length; i++) {
148
+ offsets[i] = row;
149
+ row += memo.refs[i].length;
150
+ }
151
+ return offsets;
152
+ }
98
153
  render(width) {
99
154
  const n = this.children.length;
100
155
  const memo = this.renderMemo;
@@ -119,6 +174,70 @@ export class Container {
119
174
  return lines;
120
175
  }
121
176
  }
177
+ /**
178
+ * A child that can be taken off screen without disturbing the diff.
179
+ *
180
+ * Hiding a component naively — returning `[]` from its render — is one of the
181
+ * more expensive things you can do to this renderer. `Container.render` and the
182
+ * root's flat cache both decide "did this subtree change" by **array identity**,
183
+ * so a fresh `[]` every frame reads as a change every frame: the memo is
184
+ * dropped, the buffer is re-flattened, and a dirty range is reported for a
185
+ * component that is not even drawn. One frozen array, returned every time,
186
+ * makes a hidden slot free instead.
187
+ *
188
+ * The child is not rendered at all while hidden, which is the other half of the
189
+ * saving — a hidden footer costs nothing to keep hidden. That means a child
190
+ * whose `render` advances an animation or maintains a cache will be paused, not
191
+ * merely invisible; it catches up when shown again. Chrome (footers, panels,
192
+ * status rows) is fine with that. A spinner is not, so do not wrap one.
193
+ */
194
+ export class Slot {
195
+ component;
196
+ /** Shared across every hidden slot: identity is all the caches compare. */
197
+ static EMPTY = Object.freeze([]);
198
+ hidden = false;
199
+ constructor(component) {
200
+ this.component = component;
201
+ }
202
+ /** Whoever is in the slot right now. */
203
+ get child() {
204
+ return this.component;
205
+ }
206
+ /**
207
+ * Swap the occupant, keeping the slot itself in place.
208
+ *
209
+ * An extension replacing the footer used to remove one root child and append
210
+ * another, which both moved the footer to the end of the tree — behind the
211
+ * widgets meant to sit below it — and handed the root's per-child cache a
212
+ * changed child list every time. The slot is the stable root child; only what
213
+ * is inside it changes.
214
+ */
215
+ setChild(component) {
216
+ if (this.component === component)
217
+ return false;
218
+ this.component = component;
219
+ return true;
220
+ }
221
+ get visible() {
222
+ return !this.hidden;
223
+ }
224
+ /** Returns whether this changed anything, so callers can skip a render. */
225
+ setVisible(visible) {
226
+ const hidden = !visible;
227
+ if (this.hidden === hidden)
228
+ return false;
229
+ this.hidden = hidden;
230
+ return true;
231
+ }
232
+ invalidate() {
233
+ this.child.invalidate?.();
234
+ }
235
+ render(width) {
236
+ if (this.hidden)
237
+ return Slot.EMPTY;
238
+ return this.child.render(width);
239
+ }
240
+ }
122
241
  /**
123
242
  * TUI - Main class for managing terminal UI with differential rendering
124
243
  */
@@ -165,6 +284,85 @@ export class TUI extends Container {
165
284
  previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves
166
285
  fullRedrawCount = 0;
167
286
  stopped = false;
287
+ /**
288
+ * The filler that keeps the app the size of the screen.
289
+ *
290
+ * ## Why the app is full-screen at all
291
+ *
292
+ * This renderer appends: a frame is the whole component tree flattened into
293
+ * a line buffer, written from wherever the cursor happens to be. On a fresh
294
+ * session that buffer is a dozen rows, so the banner sat halfway up a
295
+ * terminal with the prompt under it and forty rows of the user's shell
296
+ * history above — and the prompt walked down the screen as the conversation
297
+ * grew, only reaching the bottom row once the session was long enough to
298
+ * scroll. Two different layouts for the same app, and the one you meet first
299
+ * is the one that does not look like an app.
300
+ *
301
+ * ## What this does
302
+ *
303
+ * Before the frame is diffed, the root measures it and gives the leftover
304
+ * rows to one designated child. The buffer is therefore never shorter than
305
+ * the terminal, so the terminal's last row is always the buffer's last row:
306
+ * the header stays at the top, the prompt and the footer stay on the bottom,
307
+ * and everything between them is conversation. Nothing else changes — this
308
+ * is still the normal screen, so scrollback, selection and search all still
309
+ * work, and the session is still on screen after you quit.
310
+ *
311
+ * Set to `undefined` (no flex child) and the old append-only behaviour is
312
+ * exactly what you get back, which is what the tests that predate this and
313
+ * any embedder outside the app rely on.
314
+ */
315
+ flexSpacer;
316
+ /**
317
+ * The pinned viewport.
318
+ *
319
+ * ## What is wrong with letting the terminal do it
320
+ *
321
+ * This renderer keeps the entire transcript in its line buffer and writes it
322
+ * to the normal screen, so "scrolling" has always meant the terminal's own
323
+ * scrollback. That works exactly as long as the app does not repaint — and
324
+ * this one repaints the whole buffer whenever a line *above* the viewport
325
+ * changes, because a positional diff cannot address a row that has scrolled
326
+ * out of reach. The repaint is `\x1b[2J\x1b[H\x1b[3J` followed by the
327
+ * transcript again, and the `\x1b[3J` throws away the scrollback the reader
328
+ * was sitting in. From the reader's side the screen simply jumps to the
329
+ * bottom, for no reason they can see, at a moment they did not choose.
330
+ *
331
+ * ## What this does instead
332
+ *
333
+ * `scrollOffset` is the transcript row drawn at the top of the screen, and
334
+ * `null` means "follow the tail", which is the normal live behaviour and the
335
+ * path everything else in this file was written for. The moment it is a
336
+ * number the TUI switches to the alternate screen and paints a window of the
337
+ * buffer itself: a fixed grid, addressed row by row, with no scrollback for
338
+ * anything to fight over. New output still arrives and still lands in the
339
+ * buffer — it just does not move the window, which is the whole point. The
340
+ * indicator on the last row says how far down the transcript the window is,
341
+ * because a view that cannot move on its own needs to say where it stopped.
342
+ *
343
+ * Going back to live leaves the alternate screen, which restores the normal
344
+ * screen *and its scrollback* exactly as they were, and the next frame is an
345
+ * ordinary differential one that writes only what arrived while the reader
346
+ * was away — see `scrollToLive` for what has to be true for that to be safe.
347
+ * Not a clear-and-replay: on a long session that is a visible flash, a burst
348
+ * of output, and the loss of the scrollback that had just been handed back.
349
+ */
350
+ scrollOffset = null;
351
+ /** Transcript length measured by the last pinned paint; what clamping uses. */
352
+ scrollTotalLines = 0;
353
+ scrollStatusFormatter = defaultScrollStatus;
354
+ /** The running search: its query, the rows it matched, and where in them. */
355
+ scrollSearch = null;
356
+ /**
357
+ * Whether the view may pin right now.
358
+ *
359
+ * The wheel is answered wherever it is turned, including with a picker on
360
+ * screen — and a picker that lost its arrow keys to a pinned view it did not
361
+ * know about would be far worse than a wheel that did nothing. The app sets
362
+ * this because only the app knows which of its surfaces is asking a question.
363
+ * Unset means always.
364
+ */
365
+ canPinScroll;
168
366
  // Overlay stack for modal components rendered on top of base content
169
367
  focusOrderCounter = 0;
170
368
  overlayStack = [];
@@ -178,6 +376,317 @@ export class TUI extends Container {
178
376
  get fullRedraws() {
179
377
  return this.fullRedrawCount;
180
378
  }
379
+ // ── The pinned viewport ─────────────────────────────────────────────────
380
+ /** True while the view is pinned rather than following the tail. */
381
+ get scrollPinned() {
382
+ return this.scrollOffset !== null;
383
+ }
384
+ /** Where the pinned window sits, or null while live. */
385
+ getScrollPosition() {
386
+ if (this.scrollOffset === null)
387
+ return null;
388
+ return { top: this.scrollOffset, total: this.scrollTotalLines, viewHeight: this.scrollViewHeight() };
389
+ }
390
+ /** Let the app paint the indicator in its own theme. */
391
+ setScrollStatusFormatter(formatter) {
392
+ this.scrollStatusFormatter = formatter;
393
+ }
394
+ /**
395
+ * Nominate the child that absorbs the leftover rows (see `flexSpacer`).
396
+ *
397
+ * It must already be a child of the root, and it should sit between the part
398
+ * of the tree that flows from the top and the chrome that hangs off the
399
+ * bottom — everything after it is what gets pinned to the foot of the screen.
400
+ */
401
+ setFlexSpacer(spacer) {
402
+ this.flexSpacer = spacer;
403
+ }
404
+ /**
405
+ * Give the flex child whatever the frame did not use, at `height` rows.
406
+ *
407
+ * Returns true when the height moved, meaning the caller has to flatten
408
+ * again — the measurement can only be made from a finished frame, so the
409
+ * frame that answers it is always the second one. Both passes are cheap
410
+ * after the first: every other child returns its memoized array untouched.
411
+ */
412
+ fitFlexSpacer(lines, height) {
413
+ const spacer = this.flexSpacer;
414
+ if (!spacer)
415
+ return false;
416
+ return spacer.setHeight(height - (lines.length - spacer.currentHeight));
417
+ }
418
+ /**
419
+ * The screen rows a pinned window shows, the last one being the indicator.
420
+ *
421
+ * The indicator is not optional: a pinned view looks exactly like a live one
422
+ * that has gone quiet, and a reader who cannot tell the two apart will wait
423
+ * for output that is arriving perfectly well just out of sight.
424
+ */
425
+ scrollViewHeight() {
426
+ return Math.max(1, this.terminal.rows - 1);
427
+ }
428
+ /** Rows available to scroll through — the live buffer while live, the
429
+ * measured one while pinned. The filler is not transcript: counting it would
430
+ * let a session with nothing above the fold pin itself one row off the
431
+ * bottom and paint a screen of blanks. */
432
+ transcriptLength() {
433
+ if (this.scrollOffset !== null)
434
+ return this.scrollTotalLines;
435
+ return this.previousLines.length - (this.flexSpacer?.currentHeight ?? 0);
436
+ }
437
+ /**
438
+ * Move the view by `delta` rows; negative is towards the start.
439
+ *
440
+ * Returns whether anything moved, so a caller can let the key fall through
441
+ * to whatever else wants it when there is nothing to scroll.
442
+ */
443
+ scrollByLines(delta) {
444
+ if (delta === 0)
445
+ return false;
446
+ // Scrolling down while already live is not "scroll to somewhere", it is a
447
+ // request for content that does not exist yet. Doing nothing is right, and
448
+ // cheap: treating it as a move would drop out of scroll mode and force a
449
+ // full repaint on every wheel notch at the bottom of the transcript.
450
+ if (this.scrollOffset === null && delta > 0)
451
+ return false;
452
+ const viewHeight = this.scrollViewHeight();
453
+ const maxOffset = Math.max(0, this.transcriptLength() - viewHeight);
454
+ if (maxOffset === 0)
455
+ return false;
456
+ const next = (this.scrollOffset ?? maxOffset) + delta;
457
+ // Reaching the end is how the pin lets go: the reader has caught up, so
458
+ // give them the live screen back rather than a pinned view of the tail
459
+ // that silently stops following.
460
+ if (next >= maxOffset)
461
+ return this.scrollToLive();
462
+ this.setScrollOffset(next);
463
+ return true;
464
+ }
465
+ /**
466
+ * Move by pages, keeping two rows of overlap.
467
+ *
468
+ * A page that moves a full screen leaves nothing in common between before
469
+ * and after, and the reader has to find their place again on every press.
470
+ * The two kept rows are what makes the jump readable.
471
+ */
472
+ scrollByPages(delta) {
473
+ const page = Math.max(1, this.scrollViewHeight() - 2);
474
+ return this.scrollByLines(delta * page);
475
+ }
476
+ /** Pin the view to the very start of the transcript. */
477
+ scrollToTop() {
478
+ const maxOffset = Math.max(0, this.transcriptLength() - this.scrollViewHeight());
479
+ if (maxOffset === 0)
480
+ return false;
481
+ if (this.scrollOffset === 0)
482
+ return false;
483
+ this.setScrollOffset(0);
484
+ return true;
485
+ }
486
+ /** Release the pin and follow the tail again. */
487
+ scrollToLive() {
488
+ if (this.scrollOffset === null)
489
+ return false;
490
+ this.scrollOffset = null;
491
+ this.scrollSearch = null;
492
+ this.terminal.setAlternateScreen(false);
493
+ // `?1049l` restores the normal screen, its scrollback and the cursor
494
+ // exactly as they were at `?1049h`, and the snapshot taken on the way in
495
+ // says what that screen holds — so the next frame can be an ordinary
496
+ // differential one that writes only what arrived while we were reading.
497
+ // Dropping the flat cache is what makes it honest: the cache has been
498
+ // patched on every pinned frame, and a patch report describing rows that
499
+ // were painted to the *alternate* screen would leave the diff addressing
500
+ // the wrong ones.
501
+ this.flatCache = undefined;
502
+ this.lastCursorPos = undefined;
503
+ this.requestRender();
504
+ return true;
505
+ }
506
+ // ── Searching the pinned view ───────────────────────────────────────────
507
+ /**
508
+ * Find rows containing `query`, and pin the view to the nearest one above.
509
+ *
510
+ * Searching *backwards* first is the `ctrl+r` convention and it is the right
511
+ * one here: what you are looking for in a session is nearly always behind
512
+ * you, and the most recent occurrence is nearly always the one you meant.
513
+ *
514
+ * Matching is over the visible text, so it finds what the screen shows
515
+ * rather than the escape sequences underneath it — a query containing a
516
+ * colour code is not something anyone ever means.
517
+ *
518
+ * Returns how many rows matched.
519
+ */
520
+ setScrollSearch(query, options = {}) {
521
+ if (query.length === 0) {
522
+ this.scrollSearch = { query, matches: [], index: -1, measuredAt: -1, typing: options.typing ?? true };
523
+ this.requestRender();
524
+ this.expediteRender();
525
+ return 0;
526
+ }
527
+ const from = this.scrollOffset ?? Math.max(0, this.transcriptLength() - 1);
528
+ const matches = this.findScrollMatches(query);
529
+ // The nearest match at or above where the eye is, else wrap to the last.
530
+ let index = -1;
531
+ for (let i = matches.length - 1; i >= 0; i--) {
532
+ if (matches[i] <= from) {
533
+ index = i;
534
+ break;
535
+ }
536
+ }
537
+ if (index === -1 && matches.length > 0)
538
+ index = matches.length - 1;
539
+ this.scrollSearch = {
540
+ query,
541
+ matches,
542
+ index,
543
+ measuredAt: this.flatLines?.length ?? this.previousLines.length,
544
+ typing: options.typing ?? true,
545
+ };
546
+ if (index >= 0)
547
+ this.scrollToRow(matches[index]);
548
+ this.requestRender();
549
+ this.expediteRender();
550
+ return matches.length;
551
+ }
552
+ /**
553
+ * Step to the next match, `-1` being further back through the session.
554
+ *
555
+ * Wraps, because a search that stops dead at the last match makes you
556
+ * retype it to get back to the first.
557
+ */
558
+ scrollSearchStep(direction) {
559
+ const search = this.scrollSearch;
560
+ if (!search || search.matches.length === 0)
561
+ return false;
562
+ const next = (search.index + direction + search.matches.length) % search.matches.length;
563
+ search.index = next;
564
+ search.typing = false;
565
+ this.scrollToRow(search.matches[next]);
566
+ this.requestRender();
567
+ this.expediteRender();
568
+ return true;
569
+ }
570
+ /** Stop typing the query but keep the matches, so n/N can step them. */
571
+ commitScrollSearch() {
572
+ if (!this.scrollSearch)
573
+ return;
574
+ this.scrollSearch.typing = false;
575
+ this.requestRender();
576
+ this.expediteRender();
577
+ }
578
+ /** Drop the search, leaving the view where it is. */
579
+ clearScrollSearch() {
580
+ if (!this.scrollSearch)
581
+ return;
582
+ this.scrollSearch = null;
583
+ this.requestRender();
584
+ this.expediteRender();
585
+ }
586
+ get scrollSearchActive() {
587
+ return this.scrollSearch !== null;
588
+ }
589
+ /** The query being searched for, or "" when there is no search. */
590
+ get scrollSearchQuery() {
591
+ return this.scrollSearch?.query ?? "";
592
+ }
593
+ scrollSearchStatus() {
594
+ const search = this.scrollSearch;
595
+ if (!search)
596
+ return undefined;
597
+ return {
598
+ query: search.query,
599
+ count: search.matches.length,
600
+ index: search.index >= 0 ? search.index + 1 : 0,
601
+ typing: search.typing,
602
+ };
603
+ }
604
+ /**
605
+ * Rows whose visible text contains `query`, case-insensitively.
606
+ *
607
+ * One pass over the buffer, run when the query changes rather than per
608
+ * frame. The results are re-measured if the transcript has grown since —
609
+ * rare while someone is reading, and wrong in a way people notice if skipped.
610
+ */
611
+ findScrollMatches(query) {
612
+ const lines = this.flatLines ?? this.previousLines;
613
+ const needle = query.toLowerCase();
614
+ const matches = [];
615
+ for (let row = 0; row < lines.length; row++) {
616
+ const line = lines[row];
617
+ if (line.length === 0)
618
+ continue;
619
+ if (stripVTControlCharacters(line).toLowerCase().includes(needle))
620
+ matches.push(row);
621
+ }
622
+ return matches;
623
+ }
624
+ /** Re-run the search if the buffer grew under it. */
625
+ refreshScrollSearch(total) {
626
+ const search = this.scrollSearch;
627
+ if (!search || search.query.length === 0 || search.measuredAt === total)
628
+ return;
629
+ search.matches = this.findScrollMatches(search.query);
630
+ search.measuredAt = total;
631
+ if (search.index >= search.matches.length)
632
+ search.index = search.matches.length - 1;
633
+ }
634
+ /**
635
+ * Mark the query where it appears in a row about to be painted.
636
+ *
637
+ * Done at paint time, over the handful of rows on screen, rather than stored
638
+ * per match — highlighting the whole buffer to show a screenful would be the
639
+ * same work multiplied by the session's length.
640
+ *
641
+ * The row is sliced by display column so the styling already in it survives:
642
+ * a match inside a coloured span keeps its colour and gains the marker.
643
+ */
644
+ highlightScrollMatches(line, query) {
645
+ const plain = stripVTControlCharacters(line);
646
+ const needle = query.toLowerCase();
647
+ const haystack = plain.toLowerCase();
648
+ let at = haystack.indexOf(needle);
649
+ if (at === -1)
650
+ return line;
651
+ let out = "";
652
+ let cursor = 0;
653
+ while (at !== -1) {
654
+ const startCol = visibleWidth(plain.slice(0, at));
655
+ const endCol = startCol + visibleWidth(plain.slice(at, at + query.length));
656
+ const fromCol = visibleWidth(plain.slice(0, cursor));
657
+ out += sliceByColumn(line, fromCol, startCol - fromCol);
658
+ // 27 turns reverse off on its own, so whatever colour the row was
659
+ // wearing underneath the match carries on afterwards.
660
+ out += `\x1b[7m${sliceByColumn(line, startCol, endCol - startCol)}\x1b[27m`;
661
+ cursor = at + query.length;
662
+ at = haystack.indexOf(needle, cursor);
663
+ }
664
+ const tailCol = visibleWidth(plain.slice(0, cursor));
665
+ out += sliceByColumn(line, tailCol, Number.MAX_SAFE_INTEGER - tailCol);
666
+ return out;
667
+ }
668
+ setScrollOffset(offset) {
669
+ const entering = this.scrollOffset === null;
670
+ // Only entry is gated. A view that is already pinned keeps responding, so
671
+ // a surface opening underneath cannot strand the reader somewhere they
672
+ // have no key to leave.
673
+ if (entering && this.canPinScroll && !this.canPinScroll())
674
+ return;
675
+ this.scrollOffset = Math.max(0, offset);
676
+ if (entering) {
677
+ // What the normal screen is left showing, frozen. Without the copy this
678
+ // stays the same array the patching render() mutates in place, so on the
679
+ // way back out it would be diffed against itself and report that nothing
680
+ // arrived while the reader was away.
681
+ this.previousLines = this.previousLines.slice();
682
+ this.terminal.setAlternateScreen(true);
683
+ this.terminal.hideCursor();
684
+ }
685
+ this.requestRender();
686
+ // Scrolling is a direct manipulation: the view has to move under the
687
+ // gesture, not one animation frame behind it.
688
+ this.expediteRender();
689
+ }
181
690
  getShowHardwareCursor() {
182
691
  return this.showHardwareCursor;
183
692
  }
@@ -201,6 +710,48 @@ export class TUI extends Container {
201
710
  setClearOnShrink(enabled) {
202
711
  this.clearOnShrink = enabled;
203
712
  }
713
+ /** The component keystrokes are currently going to. */
714
+ get focused() {
715
+ return this.focusedComponent;
716
+ }
717
+ /**
718
+ * The root's own child offsets, which the flat cache already tracks.
719
+ *
720
+ * The base implementation reads `Container.renderMemo`, which the root does
721
+ * not keep — it has `flatCache` instead, holding exactly this. Falling
722
+ * through to the base would quietly return undefined forever.
723
+ */
724
+ childRowOffsets(width) {
725
+ const cache = this.flatCache;
726
+ if (!cache || cache.width !== width)
727
+ return undefined;
728
+ return cache.offsets;
729
+ }
730
+ /**
731
+ * Pin the view so `row` is on screen, without demanding it be at the top.
732
+ *
733
+ * A jump that always parks its target on the first row throws away whatever
734
+ * led up to it, and what led up to a message is most of what makes it
735
+ * readable. A row already comfortably in view is left where it is, so
736
+ * stepping through nearby landmarks does not make the screen lurch for each
737
+ * one.
738
+ */
739
+ scrollToRow(row, options = {}) {
740
+ const viewHeight = this.scrollViewHeight();
741
+ const maxOffset = Math.max(0, this.transcriptLength() - viewHeight);
742
+ if (maxOffset === 0)
743
+ return false;
744
+ const context = options.context ?? Math.min(3, Math.max(0, viewHeight - 1));
745
+ const target = Math.max(0, Math.min(row - context, maxOffset));
746
+ if (this.scrollOffset !== null) {
747
+ const top = this.scrollOffset;
748
+ // Already visible with room to read above it: leave it alone.
749
+ if (row >= top + context && row < top + viewHeight)
750
+ return false;
751
+ }
752
+ this.setScrollOffset(target);
753
+ return this.scrollOffset === target;
754
+ }
204
755
  setFocus(component) {
205
756
  // Clear focused flag on old component
206
757
  if (isFocusable(this.focusedComponent)) {
@@ -357,6 +908,12 @@ export class TUI extends Container {
357
908
  this.terminal.write("\x1b[16t");
358
909
  }
359
910
  stop() {
911
+ // Off the alternate screen before the exit bookkeeping below, which moves
912
+ // the cursor relative to content that lives on the normal screen.
913
+ if (this.scrollOffset !== null) {
914
+ this.scrollOffset = null;
915
+ this.terminal.setAlternateScreen(false);
916
+ }
360
917
  this.stopped = true;
361
918
  if (this.renderTimer) {
362
919
  clearTimeout(this.renderTimer);
@@ -426,6 +983,14 @@ export class TUI extends Container {
426
983
  }, delay);
427
984
  }
428
985
  handleInput(data) {
986
+ // Ahead of the listeners: a mouse report that reaches a text field is
987
+ // typed into it, and a paste-detecting listener has no reason to see one.
988
+ if (this.terminal.mouseReporting) {
989
+ const remaining = this.consumeMouseReports(data);
990
+ if (remaining === null)
991
+ return;
992
+ data = remaining;
993
+ }
429
994
  if (this.inputListeners.size > 0) {
430
995
  let current = data;
431
996
  for (const listener of this.inputListeners) {
@@ -480,6 +1045,56 @@ export class TUI extends Container {
480
1045
  this.expediteRender();
481
1046
  }
482
1047
  }
1048
+ /**
1049
+ * Act on every mouse report in `data` and return what is left of it.
1050
+ *
1051
+ * Returns null when the chunk was nothing but reports. Reports arrive
1052
+ * coalesced — a flick of the wheel delivers a run of them in one read, and a
1053
+ * keystroke pressed during the flick rides along behind — so they are peeled
1054
+ * off one at a time instead of the chunk being classified as a whole.
1055
+ */
1056
+ consumeMouseReports(data) {
1057
+ // Neither introducer present is the overwhelmingly common case (every
1058
+ // ordinary keystroke), and it costs one scan of a very short string.
1059
+ if (!data.includes("\x1b[<") && !data.includes("\x1b[M"))
1060
+ return data;
1061
+ let rest = data;
1062
+ let out = "";
1063
+ let sawReport = false;
1064
+ while (rest.length > 0) {
1065
+ const length = mouseSequenceLength(rest);
1066
+ if (length === 0) {
1067
+ out += rest[0];
1068
+ rest = rest.slice(1);
1069
+ continue;
1070
+ }
1071
+ const event = parseMouseEvent(rest.slice(0, length));
1072
+ if (event)
1073
+ this.handleMouseEvent(event);
1074
+ sawReport = true;
1075
+ rest = rest.slice(length);
1076
+ }
1077
+ if (!sawReport)
1078
+ return data;
1079
+ return out.length > 0 ? out : null;
1080
+ }
1081
+ /**
1082
+ * What the mouse does.
1083
+ *
1084
+ * Only the wheel is acted on. Clicks are swallowed rather than handled:
1085
+ * reporting is on for the wheel's sake, and a click that fell through to the
1086
+ * focused component would arrive as the raw report text in whatever field
1087
+ * has focus.
1088
+ */
1089
+ handleMouseEvent(event) {
1090
+ if (event.kind === "wheelUp") {
1091
+ this.scrollByLines(-WHEEL_LINES);
1092
+ return;
1093
+ }
1094
+ if (event.kind === "wheelDown") {
1095
+ this.scrollByLines(WHEEL_LINES);
1096
+ }
1097
+ }
483
1098
  /** Run a requested render now, bypassing the coalescing delay. Used for
484
1099
  * input-driven frames where echo latency matters more than batching. */
485
1100
  expediteRender() {
@@ -931,9 +1546,96 @@ export class TUI extends Container {
931
1546
  this.lastPatch = low === Infinity && high === -1 ? null : { low: low === Infinity ? 0 : low, high, prevLength };
932
1547
  return flat;
933
1548
  }
1549
+ /**
1550
+ * Paint the pinned window onto the alternate screen.
1551
+ *
1552
+ * Deliberately not differential. The alternate screen is `rows` tall and
1553
+ * nothing else writes to it, so a whole frame is at most a screenful of
1554
+ * cells inside one synchronized-output pair — cheaper to emit than the
1555
+ * bookkeeping a diff would need, and with nothing to get out of step with.
1556
+ * The differential renderer's state is left exactly as the last live frame
1557
+ * left it, because `scrollToLive` throws it away rather than resuming from it.
1558
+ */
1559
+ renderScrollView() {
1560
+ const width = this.terminal.columns;
1561
+ const height = this.terminal.rows;
1562
+ // No fill while pinned: the window is already the height of the screen,
1563
+ // and blank rows in the buffer would be rows of the transcript the reader
1564
+ // has to scroll past. The next live frame puts it back.
1565
+ this.flexSpacer?.setHeight(0);
1566
+ let lines = this.render(width);
1567
+ // A patch computed while pinned describes rows nothing painted to the
1568
+ // normal screen, so the live path must never be handed it.
1569
+ this.lastPatch = "full";
1570
+ if (this.overlayStack.length > 0) {
1571
+ lines = this.compositeOverlays(lines, width, height);
1572
+ }
1573
+ const viewHeight = this.scrollViewHeight();
1574
+ this.scrollTotalLines = lines.length;
1575
+ const maxOffset = Math.max(0, lines.length - viewHeight);
1576
+ // The transcript can shrink under a pinned view — a pane closing, a tool
1577
+ // block collapsing — so the offset is re-clamped every frame rather than
1578
+ // only where it is set.
1579
+ const top = Math.min(Math.max(0, this.scrollOffset ?? 0), maxOffset);
1580
+ this.scrollOffset = top;
1581
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
1582
+ buffer += HIDE_CURSOR;
1583
+ // Autowrap off for the paint: a full-width row would otherwise wrap into
1584
+ // the row below it and shift the rest of the window down by one.
1585
+ buffer += "\x1b[?7l";
1586
+ this.refreshScrollSearch(lines.length);
1587
+ const query = this.scrollSearch?.query ?? "";
1588
+ for (let row = 0; row < viewHeight; row++) {
1589
+ buffer += `\x1b[${row + 1};1H\x1b[2K`;
1590
+ const line = lines[top + row];
1591
+ if (line !== undefined)
1592
+ buffer += this.emitScrollLine(line, query);
1593
+ }
1594
+ buffer += `\x1b[${height};1H\x1b[2K`;
1595
+ buffer += this.scrollStatusFormatter({
1596
+ top: top + 1,
1597
+ bottom: Math.min(top + viewHeight, lines.length),
1598
+ total: lines.length,
1599
+ viewHeight,
1600
+ atTop: top === 0,
1601
+ atBottom: top >= maxOffset,
1602
+ width,
1603
+ search: this.scrollSearchStatus(),
1604
+ });
1605
+ buffer += "\x1b[?7h";
1606
+ buffer += "\x1b[?2026l"; // End synchronized output
1607
+ this.terminal.write(buffer);
1608
+ // `previousWidth` / `previousHeight` are deliberately left describing the
1609
+ // last *live* frame. If the terminal was resized while pinned they will
1610
+ // disagree with the real size on the way out, and the live path will take
1611
+ // its full-redraw branch — which is exactly right, because the normal
1612
+ // screen `?1049l` restored was drawn at the old size.
1613
+ }
1614
+ /**
1615
+ * One transcript row, ready for the pinned window.
1616
+ *
1617
+ * Images are named rather than drawn. A kitty or iTerm image is placed by
1618
+ * the cursor and sized in pixels, so the same escape replayed at a different
1619
+ * screen row lands somewhere the window did not ask for and survives the
1620
+ * frame that was supposed to replace it — a smear across the view that no
1621
+ * later repaint can clear.
1622
+ */
1623
+ emitScrollLine(line, query = "") {
1624
+ if (isImageLine(line))
1625
+ return "\x1b[2m[image]\x1b[0m";
1626
+ const marker = line.indexOf(CURSOR_MARKER);
1627
+ let text = marker === -1 ? line : line.slice(0, marker) + line.slice(marker + CURSOR_MARKER.length);
1628
+ if (query.length > 0)
1629
+ text = this.highlightScrollMatches(text, query);
1630
+ return normalizeTerminalOutput(text) + TUI.SEGMENT_RESET;
1631
+ }
934
1632
  doRender() {
935
1633
  if (this.stopped)
936
1634
  return;
1635
+ if (this.scrollOffset !== null) {
1636
+ this.renderScrollView();
1637
+ return;
1638
+ }
937
1639
  const width = this.terminal.columns;
938
1640
  const height = this.terminal.rows;
939
1641
  const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
@@ -950,6 +1652,15 @@ export class TUI extends Container {
950
1652
  // Render all components to get new lines. The root render() reports what
951
1653
  // it changed via lastPatch; consume it here (it is per-frame state).
952
1654
  let newLines = this.render(width);
1655
+ // The frame has to exist before its leftover rows can be counted, so the
1656
+ // fill is settled by re-flattening rather than predicted. The second pass
1657
+ // invalidates the first's patch — it describes the buffer from before the
1658
+ // splice — so fall back to the full scan, which is always correct and only
1659
+ // runs on frames where the content height actually changed.
1660
+ if (this.fitFlexSpacer(newLines, height)) {
1661
+ newLines = this.render(width);
1662
+ this.lastPatch = "full";
1663
+ }
953
1664
  const patch = this.lastPatch;
954
1665
  this.lastPatch = "full";
955
1666
  // Composite overlays into the rendered lines (before differential compare)