rpi-tui 0.3.2

Terminal User Interface for pi-rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! Layout system for constrained rendering in TuiAltScreen.
//!
//! This module implements the layout system described in `tui-plan.md`:
//! - LayoutBox/LayoutFrame for tracking component positions
//! - Stack layout allocation with basis/grow/shrink
//! - Painting visible rows with clipping
//! - Hit testing for mouse events

use std::sync::Arc;

use super::component::Component;
use super::layout_node::LayoutViewport;
use super::scroll_view::ScrollView;
use super::vstack::{layout_vstack_constrained, VStack};
use crate::ansi::{slice_by_column, visible_width, CURSOR_MARKER};

/// A rectangle in the layout.
#[derive(Debug, Clone, Copy, Default)]
pub struct LayoutRect {
    pub x: usize,
    pub y: usize,
    pub width: usize,
    pub height: usize,
}

impl LayoutRect {
    pub fn new(x: usize, y: usize, width: usize, height: usize) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// Check if a point is inside this rectangle.
    pub fn contains(&self, x: usize, y: usize) -> bool {
        x >= self.x && x < self.x + self.width && y >= self.y && y < self.y + self.height
    }

    /// Intersect with another rectangle.
    pub fn intersect(&self, other: &LayoutRect) -> LayoutRect {
        let x = self.x.max(other.x);
        let y = self.y.max(other.y);
        let right = (self.x + self.width).min(other.x + other.width);
        let bottom = (self.y + self.height).min(other.y + other.height);
        LayoutRect {
            x,
            y,
            width: right.saturating_sub(x),
            height: bottom.saturating_sub(y),
        }
    }
}

/// A box in the layout tree.
#[derive(Clone)]
pub struct LayoutBox {
    /// The component this box represents.
    pub component: Arc<dyn Component>,
    /// The allocated rectangle.
    pub rect: LayoutRect,
    /// The clipping rectangle (intersection of all ancestor clips).
    pub clip: LayoutRect,
    /// Child boxes.
    pub children: Vec<LayoutBox>,
    /// Parent box index.
    pub parent_index: Option<usize>,
    /// Rendered lines (cached).
    pub lines: Option<Vec<String>>,
    /// Line offset for cursor visibility.
    pub line_offset: usize,
    /// Layer for hit testing.
    pub layer: usize,
    /// ScrollView reference if this is a scroll view.
    pub scroll_view: Option<Arc<ScrollView>>,
    /// Scroll content lines (pre-rendered).
    pub scroll_content_lines: Option<Vec<String>>,
}

impl LayoutBox {
    pub fn new(component: Arc<dyn Component>, rect: LayoutRect, clip: LayoutRect) -> Self {
        Self {
            component,
            rect,
            clip,
            children: Vec::new(),
            parent_index: None,
            lines: None,
            line_offset: 0,
            layer: 0,
            scroll_view: None,
            scroll_content_lines: None,
        }
    }
}

/// A complete layout frame for rendering.
#[derive(Clone)]
pub struct LayoutFrame {
    /// Root box.
    pub root: LayoutBox,
    /// Total width.
    pub width: usize,
    /// Total height.
    pub height: usize,
    /// Rendered screen lines.
    pub lines: Vec<String>,
    /// Primary scroll view (if any).
    pub primary_scroll_view: Option<Arc<ScrollView>>,
}

impl LayoutFrame {
    /// Create a new layout frame.
    pub fn new(root: LayoutBox, width: usize, height: usize) -> Self {
        Self {
            root,
            width,
            height,
            lines: vec![String::new(); height],
            primary_scroll_view: None,
        }
    }
}

/// Context for layout operations.
struct LayoutContext {
    #[allow(dead_code)]
    viewport: LayoutViewport,
    primary_scroll_view: Option<Arc<ScrollView>>,
    reuse_scroll_content: bool,
}

impl LayoutContext {
    fn register_scroll_view(&mut self, sv: &Arc<ScrollView>) {
        // Keep the first primary scroll view encountered (the root transcript
        // area). Non-primary scroll views are not tracked globally.
        if sv.is_primary() && self.primary_scroll_view.is_none() {
            self.primary_scroll_view = Some(sv.clone());
        }
    }
}

/// Render a component tree into a layout frame with constrained layout.
pub fn render_layout_frame(root: Arc<dyn Component>, width: usize, height: usize) -> LayoutFrame {
    render_layout_frame_impl(root, width, height, false)
}

/// Render a frame where only scroll positions and non-scroll content changed.
/// Scroll views may reuse their last full child rendering.
pub(crate) fn render_layout_frame_reusing_scroll_content(
    root: Arc<dyn Component>,
    width: usize,
    height: usize,
) -> LayoutFrame {
    render_layout_frame_impl(root, width, height, true)
}

fn render_layout_frame_impl(
    root: Arc<dyn Component>,
    width: usize,
    height: usize,
    reuse_scroll_content: bool,
) -> LayoutFrame {
    let safe_width = width.max(1);
    let safe_height = height.max(1);

    let mut context = LayoutContext {
        viewport: LayoutViewport {
            width: safe_width,
            height: safe_height,
        },
        primary_scroll_view: None,
        reuse_scroll_content,
    };

    let root_box = layout_component(
        &root,
        0,
        0,
        safe_width,
        Some(safe_height),
        LayoutRect::new(0, 0, safe_width, safe_height),
        &mut context,
    );

    let mut frame = LayoutFrame::new(root_box, safe_width, safe_height);
    frame.primary_scroll_view = context.primary_scroll_view;

    // Paint the root box into the screen lines
    paint_box(&frame.root, &mut frame.lines, safe_width);

    frame
}

/// Layout a single component and its children.
///
/// Recognizes `VStack` and `ScrollView` (via `as_any` downcast) and lays
/// them out with the existing constrained machinery, so stack `grow`/`shrink`/
/// `min_size` semantics are honored and the scroll view clips to its
/// allocated viewport. Any other component is treated as a leaf.
fn layout_component(
    component: &Arc<dyn Component>,
    x: usize,
    y: usize,
    width: usize,
    height: Option<usize>,
    clip: LayoutRect,
    context: &mut LayoutContext,
) -> LayoutBox {
    let safe_width = width.max(1);

    // VStack: distribute the available height across children according to
    // their basis/grow/shrink/min_size (mirrors TS stack layout). This was
    // previously dead — the layout engine treated the root VStack as a leaf
    // and concatenated each child's full intrinsic height, which pushed the
    // bottom dock below the visible viewport.
    if let Some(vstack) = component.as_any().downcast_ref::<VStack>() {
        return layout_vstack(component, vstack, x, y, safe_width, height, clip, context);
    }

    // ScrollView: clip the child to the allocated viewport height and render
    // only the visible window. Without this the scroll view emitted *all*
    // transcript lines, overflowing past the terminal bottom.
    if let Some(sv) = component.as_any().downcast_ref::<ScrollView>() {
        return layout_scroll_view(component, sv, x, y, safe_width, height, clip, context);
    }

    // ---- Leaf (Container/Editor/Footer/Text/...) ----
    let lines = component.render(safe_width);

    let allocated_height = height.unwrap_or_else(|| lines.len());

    // Calculate line offset for cursor visibility
    let line_offset = if lines.len() > allocated_height && allocated_height > 0 {
        let cursor_line = lines.iter().position(|line| line.contains(CURSOR_MARKER));
        cursor_line
            .map(|idx| {
                if idx >= allocated_height {
                    idx - allocated_height + 1
                } else {
                    0
                }
            })
            .unwrap_or(0)
    } else {
        0
    };

    let rect = LayoutRect::new(x, y, safe_width, allocated_height);

    LayoutBox {
        component: component.clone(),
        rect,
        clip: clip.intersect(&rect),
        children: Vec::new(),
        parent_index: None,
        lines: Some(lines),
        line_offset,
        layer: 0,
        scroll_view: None,
        scroll_content_lines: None,
    }
}

/// Lay out a VStack by distributing `height` across its children.
fn layout_vstack(
    component: &Arc<dyn Component>,
    vstack: &VStack,
    x: usize,
    y: usize,
    width: usize,
    height: Option<usize>,
    clip: LayoutRect,
    context: &mut LayoutContext,
) -> LayoutBox {
    let children = vstack.get_children();
    let gap = vstack.gap();
    let allocated = layout_vstack_constrained(&children, width, height.unwrap_or(0), gap);

    // The box's own rect spans its full allocated height (or, when
    // unconstrained, the sum of child heights + gaps).
    let total_child_height: usize = allocated.iter().map(|(_, h)| *h).sum();
    let total_gap = if children.len() > 1 {
        gap * (children.len() - 1)
    } else {
        0
    };
    let box_height = height.unwrap_or(total_child_height + total_gap);

    let rect = LayoutRect::new(x, y, width, box_height);
    let own_clip = clip.intersect(&rect);

    let mut child_boxes = Vec::with_capacity(allocated.len());
    let mut cursor_y = y;
    for (idx, (child_component, child_height)) in allocated.iter().enumerate() {
        if idx > 0 && gap > 0 {
            cursor_y = cursor_y.saturating_add(gap);
        }
        let child_box = layout_component(
            child_component,
            x,
            cursor_y,
            width,
            Some(*child_height),
            own_clip,
            context,
        );
        // `parent_index` is the child's ordinal within its parent; `paint_box`
        // does not rely on it, but `hit_test` walks children front-to-back so
        // keeping the positional index is harmless.
        child_boxes.push(child_box);
        cursor_y = cursor_y.saturating_add(*child_height);
    }
    for (i, child) in child_boxes.iter_mut().enumerate() {
        child.parent_index = Some(i);
        child.layer = 0;
    }

    // The parent box carries no lines of its own — its children paint into
    // the screen buffer directly via `paint_box` recursion.
    let mut box_layout = LayoutBox::new(component.clone(), rect, own_clip);
    box_layout.children = child_boxes;
    box_layout
}

/// Lay out a ScrollView by clipping its child to the allocated viewport.
fn layout_scroll_view(
    component: &Arc<dyn Component>,
    sv: &ScrollView,
    x: usize,
    y: usize,
    width: usize,
    height: Option<usize>,
    clip: LayoutRect,
    context: &mut LayoutContext,
) -> LayoutBox {
    // Track the primary scroll view globally so `get_primary_scroll_view`
    // returns the live transcript area.
    let sv_arc: Arc<ScrollView> = Arc::new(sv.clone());
    context.register_scroll_view(&sv_arc);

    let allocated_height = height.unwrap_or_else(|| sv.render(width).len());
    // Cached frames are used only for pure viewport movement or animation in
    // the bottom dock. Ordinary content updates always refresh this cache.
    let lines = if context.reuse_scroll_content {
        sv.render_with_cached_content(width, allocated_height)
    } else {
        sv.render_with_viewport(width, allocated_height)
    };

    let line_offset = if lines.len() > allocated_height && allocated_height > 0 {
        let cursor_line = lines.iter().position(|line| line.contains(CURSOR_MARKER));
        cursor_line
            .map(|idx| {
                if idx >= allocated_height {
                    idx - allocated_height + 1
                } else {
                    0
                }
            })
            .unwrap_or(0)
    } else {
        0
    };

    let rect = LayoutRect::new(x, y, width, allocated_height);

    LayoutBox {
        component: component.clone(),
        rect,
        clip: clip.intersect(&rect),
        children: Vec::new(),
        parent_index: None,
        lines: Some(lines),
        line_offset,
        layer: 0,
        scroll_view: Some(sv_arc),
        scroll_content_lines: None,
    }
}

/// Translate a box and its children by a delta.
#[allow(dead_code)]
fn translate_box(lbox: &mut LayoutBox, delta_y: i32) {
    if delta_y >= 0 {
        lbox.rect.y += delta_y as usize;
    } else {
        lbox.rect.y = lbox.rect.y.saturating_sub((-delta_y) as usize);
    }
    for child in &mut lbox.children {
        translate_box(child, delta_y);
    }
}

/// Update clips for a box and its children.
#[allow(dead_code)]
fn update_clips(lbox: &mut LayoutBox, parent_clip: LayoutRect) {
    lbox.clip = parent_clip.intersect(&lbox.rect);
    let child_clip = lbox.clip;
    for child in &mut lbox.children {
        update_clips(child, child_clip);
    }
}

/// Paint a box and its children into the screen buffer.
fn paint_box(lbox: &LayoutBox, screen: &mut [String], total_width: usize) {
    if let Some(ref lines) = lbox.lines {
        let offset = lbox.line_offset;

        // Calculate visible row range
        let first_row = lbox.rect.y.max(lbox.clip.y);
        let last_row = (lbox.rect.y + lbox.rect.height)
            .min(lbox.clip.y + lbox.clip.height)
            .min(screen.len());

        for row in first_row..last_row {
            if row >= screen.len() {
                break;
            }

            let source_idx = offset + row.saturating_sub(lbox.rect.y);
            if source_idx >= lines.len() {
                break;
            }

            let source_line = &lines[source_idx];

            // Composite the line into the screen
            if lbox.rect.x == 0 && lbox.rect.width >= total_width {
                // Fast path: full-width box at left edge
                screen[row] = source_line.clone();
            } else {
                // Composite at the correct position
                screen[row] = composite_tui_line(
                    &screen[row],
                    source_line,
                    lbox.rect.x,
                    lbox.rect.width,
                    total_width,
                );
            }
        }
    }

    // Paint children
    for child in &lbox.children {
        paint_box(child, screen, total_width);
    }
}

/// Composite an overlay line onto a base line at a given column position.
pub fn composite_tui_line(
    base: &str,
    overlay: &str,
    start_col: usize,
    overlay_width: usize,
    total_width: usize,
) -> String {
    let base_width = visible_width(base);
    let overlay_actual_width = visible_width(overlay);

    // If overlay is empty or starts beyond total width, return base
    if overlay_actual_width == 0 || start_col >= total_width {
        return base.to_string();
    }

    // Calculate the portion of overlay that fits
    let effective_width = overlay_width.min(total_width.saturating_sub(start_col));

    // Slice or pad overlay to effective width
    let overlay_padded = if overlay_actual_width < effective_width {
        // Pad right
        format!(
            "{}{}",
            overlay,
            " ".repeat(effective_width - overlay_actual_width)
        )
    } else if overlay_actual_width > effective_width {
        // Truncate
        slice_by_column(overlay, 0, effective_width, true)
    } else {
        overlay.to_string()
    };

    // Build the composite line
    let before_width = start_col.min(base_width);
    let after_start = start_col + effective_width;

    // Get before portion from base
    let before = if before_width > 0 {
        slice_by_column(base, 0, before_width, true)
    } else {
        String::new()
    };

    // Get after portion from base
    let after = if after_start < base_width {
        slice_by_column(
            base,
            after_start,
            base_width.saturating_sub(after_start),
            true,
        )
    } else {
        String::new()
    };

    // Combine with resets to prevent style leakage
    const SEGMENT_RESET: &str = "\x1b[0m\x1b]8;;\x07";

    // Calculate padding
    let before_pad = if visible_width(&before) < before_width {
        " ".repeat(before_width - visible_width(&before))
    } else {
        String::new()
    };

    let after_pad = if after_start < total_width {
        let expected_after_width = total_width.saturating_sub(after_start);
        let actual_after_width = visible_width(&after);
        if actual_after_width < expected_after_width {
            " ".repeat(expected_after_width - actual_after_width)
        } else {
            String::new()
        }
    } else {
        String::new()
    };

    format!(
        "{}{}{}{}{}{}{}",
        before, before_pad, SEGMENT_RESET, overlay_padded, SEGMENT_RESET, after, after_pad
    )
}

/// Hit test to find the deepest box at a given coordinate.
pub fn hit_test(frame: &LayoutFrame, x: usize, y: usize) -> Option<&LayoutBox> {
    hit_test_box(&frame.root, x, y)
}

fn hit_test_box(lbox: &LayoutBox, x: usize, y: usize) -> Option<&LayoutBox> {
    // Check if point is in clip
    if !lbox.clip.contains(x, y) {
        return None;
    }

    // Check if point is in rect
    if !lbox.rect.contains(x, y) {
        return None;
    }

    // Check children first (front to back)
    for child in lbox.children.iter().rev() {
        if let Some(hit) = hit_test_box(child, x, y) {
            return Some(hit);
        }
    }

    // Return this box if no child was hit
    Some(lbox)
}

/// Find all scroll views at a given coordinate.
pub fn get_scroll_views_at(frame: &LayoutFrame, x: usize, y: usize) -> Vec<Arc<ScrollView>> {
    let mut result = Vec::new();
    collect_scroll_views(&frame.root, x, y, &mut result);
    result
}

fn collect_scroll_views(lbox: &LayoutBox, x: usize, y: usize, result: &mut Vec<Arc<ScrollView>>) {
    if !lbox.clip.contains(x, y) || !lbox.rect.contains(x, y) {
        return;
    }

    if let Some(ref sv) = lbox.scroll_view {
        result.push(sv.clone());
    }

    for child in &lbox.children {
        collect_scroll_views(child, x, y, result);
    }
}

/// Extract cursor position from rendered lines.
pub fn extract_cursor_position(lines: &[String], height: usize) -> Option<(usize, usize)> {
    let viewport_top = lines.len().saturating_sub(height);

    for row in (viewport_top..lines.len()).rev() {
        let line = &lines[row];
        if let Some(marker_idx) = line.find(CURSOR_MARKER) {
            let before = &line[..marker_idx];
            let col = visible_width(before);
            return Some((row, col));
        }
    }

    None
}

/// Strip cursor markers from lines.
pub fn strip_cursor_markers(lines: &[String]) -> Vec<String> {
    lines
        .iter()
        .map(|line| line.replace(CURSOR_MARKER, ""))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        Container, Editor, EditorOptions, EditorStyle, Focusable, ScrollView, ScrollViewOptions,
        StackChild, StackEntry, Text, VStack,
    };

    #[test]
    fn test_layout_rect_contains() {
        let rect = LayoutRect::new(5, 5, 10, 10);
        assert!(rect.contains(5, 5)); // Top-left corner
        assert!(rect.contains(10, 10)); // Inside
        assert!(!rect.contains(4, 5)); // Left of
        assert!(!rect.contains(15, 5)); // Right of
        assert!(!rect.contains(5, 15)); // Below
    }

    #[test]
    fn test_layout_rect_intersect() {
        let a = LayoutRect::new(0, 0, 10, 10);
        let b = LayoutRect::new(5, 5, 10, 10);
        let c = a.intersect(&b);
        assert_eq!(c.x, 5);
        assert_eq!(c.y, 5);
        assert_eq!(c.width, 5);
        assert_eq!(c.height, 5);
    }

    #[test]
    fn test_composite_tui_line() {
        let base = "Hello, World!";
        let overlay = "Rust";
        let result = composite_tui_line(base, overlay, 7, 4, 20);
        assert!(result.contains("Hello,"));
        assert!(result.contains("Rust"));
    }

    #[test]
    fn test_render_layout_frame() {
        let text = Arc::new(Text::new("Hello, World!", 0, 0));
        let frame = render_layout_frame(text, 20, 10);
        assert_eq!(frame.width, 20);
        assert_eq!(frame.height, 10);
        assert!(!frame.lines.is_empty());
    }

    /// Regression for the leaf-only layout bug: a root `VStack[ scrollview
    /// (grow1), dock ]` must pin the dock (editor borders + footer) to the
    /// bottom of the viewport and clip the scrollview to the remainder. Before
    /// the fix the dock was pushed below the visible rows and the screen was
    /// black where the editor should be.
    #[test]
    fn test_constrained_layout_dock_pinned_to_bottom() {
        // Tall transcript (many lines) so the scrollview's intrinsic height
        // exceeds the viewport — it must be clipped, not overflow.
        let transcript = Arc::new(Container::new());
        for i in 0..40 {
            transcript.add_child(Arc::new(Text::new(&format!("line {i:02}"), 0, 0)));
        }
        let scroll = Arc::new(ScrollView::new(
            transcript,
            // FollowMode::None so the scrollview doesn't jump to the end
            // (which would push the first 30 lines off-screen) — we want to
            // assert the top of the transcript is visible, i.e. clipped, not
            // that it rendered *all* 40 lines.
            ScrollViewOptions {
                follow: crate::FollowMode::None,
                ..Default::default()
            },
        ));

        let editor = Arc::new(Editor::new(
            EditorOptions::default(),
            EditorStyle::default(),
            Arc::new(crate::Keybindings::new()),
        ));
        editor.set_focused(true);
        let editor_container = Arc::new(Container::new());
        editor_container.add_child(editor.clone());
        let footer = Arc::new(Text::new("FOOTER LINE", 0, 0));

        let dock = Arc::new(VStack::from_children(vec![
            StackChild::Entry(
                StackEntry::new(editor_container.clone())
                    .shrink(0)
                    .min_size(3),
            ),
            StackChild::Entry(StackEntry::new(footer.clone())),
        ]));

        let root = VStack::from_children(vec![
            StackChild::Entry(
                StackEntry::new(scroll.clone())
                    .basis(0)
                    .grow(1)
                    .shrink(1)
                    .min_size(1),
            ),
            StackChild::Entry(StackEntry::new(dock).shrink(1)),
        ]);

        // 40-col wide, 10-row tall viewport.
        let frame = render_layout_frame(Arc::new(root), 40, 10);

        // The screen buffer must be exactly the viewport height.
        assert_eq!(
            frame.lines.len(),
            10,
            "frame should be clipped to viewport height"
        );

        // The dock (editor borders + footer) must occupy the bottom rows of
        // the painted screen — the editor renders 3 rows (top border, content,
        // bottom border) + the footer 1 row = 4 dock rows. The bottom-most
        // painted row must be the footer.
        let bottom = frame.lines.last().expect("non-empty frame");
        assert!(
            bottom.contains("FOOTER"),
            "footer should be the last painted row; got: {bottom:?}"
        );

        // The editor's top border (a run of `─`) must appear on-screen just
        // above the footer region. Borders are colored via the theme border
        // color, so check for the `─` glyph rather than a raw repeat.
        let on_screen: String = frame.lines.join("\n");
        assert!(
            on_screen.contains('─'),
            "editor top border `─` should be visible on-screen; rendered:\n{on_screen}"
        );

        // The scrollview must NOT paint all 40 transcript lines — it must be
        // clipped to the top rows. "line 39" (the last) must be absent.
        assert!(
            !on_screen.contains("line 39"),
            "scrollview should be clipped to the viewport, not render all 40 lines"
        );

        // Primary scroll view should be tracked so get_primary_scroll_view /
        // frame.primary_scroll_view is populated for the scroll routing.
        // (The default ScrollView is non-primary; skip that assertion here and
        // rely on the is_primary branch in layout_scroll_view.)
    }
}

#[cfg(test)]
mod scroll_layout_tests {
    use super::*;
    use crate::component::Component;
    use crate::{Container, ScrollView, ScrollViewOptions, Text};
    use std::any::Any;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct CountingTranscript {
        renders: Arc<AtomicUsize>,
    }

    impl Component for CountingTranscript {
        fn render(&self, _width: usize) -> Vec<String> {
            self.renders.fetch_add(1, Ordering::SeqCst);
            (0..100).map(|i| format!("row {i:03}")).collect()
        }

        fn invalidate(&self) {}

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    fn tall() -> (Arc<ScrollView>, Arc<Container>) {
        let inner = Arc::new(Container::new());
        for i in 0..50 {
            inner.add_child(Arc::new(Text::new(format!("row {i:02}"), 0, 0)));
        }
        let sv = Arc::new(ScrollView::new(
            inner.clone(),
            ScrollViewOptions {
                follow: crate::FollowMode::End,
                primary: true,
                ..Default::default()
            },
        ));
        (sv, inner)
    }

    #[test]
    fn layout_scroll_view_respects_scroll_top() {
        let (sv, _) = tall();
        let root: Arc<dyn Component> = sv.clone();
        // Initial: following end → tail visible.
        let f1 = render_layout_frame(root.clone(), 40, 10);
        assert!(
            f1.lines[0].contains("row 40"),
            "tail visible: {:?}",
            f1.lines[0]
        );
        // Scroll up, then re-layout: older rows must appear.
        sv.scroll_by(-10);
        let f2 = render_layout_frame(root, 40, 10);
        assert!(
            f2.lines[0].contains("row 30"),
            "after scroll-up, row 30 top: {:?}",
            f2.lines[0]
        );
    }

    #[test]
    fn scroll_frames_reuse_rendered_transcript() {
        let renders = Arc::new(AtomicUsize::new(0));
        let transcript = Arc::new(CountingTranscript {
            renders: renders.clone(),
        });
        let scroll = Arc::new(ScrollView::new(
            transcript,
            ScrollViewOptions {
                follow: crate::FollowMode::End,
                primary: true,
                ..Default::default()
            },
        ));
        let root: Arc<dyn Component> = Arc::new(VStack::from_children(vec![
            crate::StackChild::Entry(
                crate::StackEntry::new(scroll.clone())
                    .basis(0)
                    .grow(1)
                    .min_size(1),
            ),
            crate::StackChild::Entry(crate::StackEntry::new(Arc::new(Text::new("dock", 0, 0)))),
        ]));

        render_layout_frame(root.clone(), 40, 10);
        assert_eq!(renders.load(Ordering::SeqCst), 1);

        scroll.scroll_by(-1);
        render_layout_frame_reusing_scroll_content(root.clone(), 40, 10);
        assert_eq!(
            renders.load(Ordering::SeqCst),
            1,
            "pure scrolling must not rebuild the transcript",
        );

        render_layout_frame(root.clone(), 40, 10);
        assert_eq!(
            renders.load(Ordering::SeqCst),
            2,
            "ordinary frames must refresh mutable transcript content",
        );

        render_layout_frame_reusing_scroll_content(root, 60, 10);
        assert_eq!(
            renders.load(Ordering::SeqCst),
            3,
            "a width change must invalidate wrapped transcript lines",
        );
    }
}