gravityfile-tui 0.4.1

Terminal user interface for gravityfile
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
//! Directory tree widget.

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, StatefulWidget, Widget};

use gravityfile_core::{FileNode, GitStatus, NodeKind};
use unicode_width::UnicodeWidthStr;

use crate::app::state::{ClipboardMode, ClipboardState};
use crate::theme::Theme;
use crate::ui::{CompactSizeBar, fit_to_width, format_size};

/// State for the tree view.
#[derive(Debug, Default, Clone)]
pub struct TreeState {
    /// Currently selected index in the flattened view.
    pub selected: usize,
    /// Scroll offset.
    pub offset: usize,
    /// Set of expanded directory paths.
    pub expanded: HashSet<PathBuf>,
}

impl TreeState {
    /// Create new tree state with the root expanded.
    pub fn new(root_path: PathBuf) -> Self {
        Self {
            selected: 0,
            offset: 0,
            expanded: HashSet::from([root_path]),
        }
    }

    /// Toggle expansion of a path.
    pub fn toggle_expand(&mut self, path: &Path) {
        if self.expanded.contains(path) {
            self.expanded.remove(path);
        } else {
            self.expanded.insert(path.to_path_buf());
        }
    }

    /// Expand a path.
    pub fn expand(&mut self, path: &Path) {
        self.expanded.insert(path.to_path_buf());
    }

    /// Collapse a path.
    pub fn collapse(&mut self, path: &Path) {
        self.expanded.remove(path);
    }

    /// Check if a path is expanded.
    pub fn is_expanded(&self, path: &PathBuf) -> bool {
        self.expanded.contains(path)
    }

    /// Move selection up.
    pub fn move_up(&mut self, count: usize) {
        self.selected = self.selected.saturating_sub(count);
    }

    /// Move selection down.
    pub fn move_down(&mut self, count: usize, max: usize) {
        self.selected = (self.selected + count).min(max.saturating_sub(1));
    }

    /// Jump to top.
    pub fn jump_to_top(&mut self) {
        self.selected = 0;
    }

    /// Jump to bottom.
    pub fn jump_to_bottom(&mut self, max: usize) {
        self.selected = max.saturating_sub(1);
    }

    /// Ensure selected item is visible, adjusting offset if needed.
    pub fn ensure_visible(&mut self, viewport_height: usize) {
        if self.selected < self.offset {
            self.offset = self.selected;
        } else if self.selected >= self.offset + viewport_height {
            self.offset = self.selected - viewport_height + 1;
        }
    }
}

/// A flattened visible item in the tree.
#[derive(Debug, Clone)]
pub struct VisibleItem {
    pub path: PathBuf,
    pub node: VisibleNode,
    pub depth: usize,
    pub is_last_sibling: bool,
    pub parent_last_siblings: Vec<bool>,
}

/// Lightweight node info for display.
#[derive(Debug, Clone)]
pub struct VisibleNode {
    pub name: String,
    pub size: u64,
    pub kind: VisibleNodeKind,
    pub git_status: Option<GitStatus>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VisibleNodeKind {
    Directory { expanded: bool },
    File { executable: bool },
    Symlink { broken: bool },
    Other,
}

/// Tree view widget.
pub struct TreeView<'a> {
    root: &'a FileNode,
    root_path: &'a PathBuf,
    total_size: u64,
    theme: &'a Theme,
    marked: &'a HashSet<PathBuf>,
    clipboard: &'a ClipboardState,
    block: Option<Block<'a>>,
}

impl<'a> TreeView<'a> {
    /// Create a new tree view.
    pub fn new(
        root: &'a FileNode,
        root_path: &'a PathBuf,
        theme: &'a Theme,
        marked: &'a HashSet<PathBuf>,
        clipboard: &'a ClipboardState,
    ) -> Self {
        Self {
            root,
            root_path,
            total_size: root.size,
            theme,
            marked,
            clipboard,
            block: None,
        }
    }

    /// Set the block (border) for the widget.
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    /// Every visible row, in order.
    pub fn flatten(&self, state: &TreeState) -> Vec<VisibleItem> {
        self.rows(state, 0..usize::MAX)
    }

    /// The visible row at `index`.
    pub fn row(&self, state: &TreeState, index: usize) -> Option<VisibleItem> {
        self.rows(state, index..index.saturating_add(1)).pop()
    }

    /// The visible rows whose positions fall in `range`. Rows outside it are
    /// counted but not built, so a frame costs the rows on screen plus a pass
    /// over expanded directories, not an allocation per visible entry.
    pub fn rows(&self, state: &TreeState, range: std::ops::Range<usize>) -> Vec<VisibleItem> {
        let mut items = Vec::new();
        self.walk(state, range, |_, item| items.push(item()));
        items
    }

    /// The number of visible rows.
    pub fn flatten_count(&self, state: &TreeState) -> usize {
        self.walk(state, usize::MAX..usize::MAX, |_, _| {})
    }

    /// The row showing `target`, if it is visible.
    pub fn position(&self, state: &TreeState, target: &Path) -> Option<usize> {
        if !target.starts_with(self.root_path) {
            return None;
        }
        let (mut index, mut found) = (0, None);
        self.walk(state, 0..usize::MAX, |path, _| {
            if found.is_none() && path == target {
                found = Some(index);
            }
            index += 1;
        });
        found
    }

    /// Visit the visible rows in `range`, in order, giving `visit` each row's
    /// path and a way to build it. Rows before the range are only counted.
    /// Iterative, so deep expanded trees cannot exhaust the stack. Returns
    /// the number of rows walked.
    fn walk(
        &self,
        state: &TreeState,
        range: std::ops::Range<usize>,
        mut visit: impl FnMut(&Path, &dyn Fn() -> VisibleItem),
    ) -> usize {
        let stop = range.end;
        let build =
            |node: &FileNode, path: &Path, depth, is_last, lasts: &[bool], expanded| VisibleItem {
                path: path.to_path_buf(),
                node: VisibleNode {
                    name: node.display_name().into_owned(),
                    size: node.size,
                    kind: match &node.kind {
                        NodeKind::Directory { .. } => VisibleNodeKind::Directory { expanded },
                        NodeKind::File { executable } => VisibleNodeKind::File {
                            executable: *executable,
                        },
                        NodeKind::Symlink { broken, .. } => {
                            VisibleNodeKind::Symlink { broken: *broken }
                        }
                        NodeKind::Other => VisibleNodeKind::Other,
                    },
                    git_status: node.git_status,
                },
                depth,
                is_last_sibling: is_last,
                parent_last_siblings: lasts.to_vec(),
            };
        if stop == 0 {
            return 0;
        }
        let mut path = self.root_path.clone();
        let root_expanded = state.is_expanded(&path);
        if range.contains(&0) {
            visit(&path, &|| {
                build(self.root, &path, 0, true, &[], root_expanded)
            });
        }
        let mut index = 1;
        if !(root_expanded && self.root.is_dir()) {
            return index;
        }
        // Each open directory's remaining children, and whether each
        // ancestor was its parent's last child (for the guide lines).
        let mut stack = vec![(
            self.root.children.iter().enumerate(),
            self.root.children.len(),
        )];
        let mut lasts = vec![true];
        while let Some((children, count)) = stack.last_mut() {
            if index >= stop {
                break;
            }
            let count = *count;
            let Some((position, child)) = children.next() else {
                stack.pop();
                lasts.pop();
                path.pop();
                continue;
            };
            if index < range.start && !child.is_dir() {
                // Nothing below a file, so it is one row to count.
                index += 1;
                continue;
            }
            let is_last = position + 1 == count;
            let depth = stack.len();
            path.push(child.file_name());
            let expanded = child.is_dir() && state.is_expanded(&path);
            if index >= range.start {
                visit(&path, &|| {
                    build(child, &path, depth, is_last, &lasts, expanded)
                });
            }
            index += 1;
            if expanded && !child.children.is_empty() {
                lasts.push(is_last);
                stack.push((child.children.iter().enumerate(), child.children.len()));
            } else {
                path.pop();
            }
        }
        index
    }
}

impl StatefulWidget for TreeView<'_> {
    type State = TreeState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        // Handle block/border
        let inner_area = if let Some(block) = &self.block {
            let inner = block.inner(area);
            block.clone().render(area, buf);
            inner
        } else {
            area
        };

        if inner_area.height == 0 || inner_area.width == 0 {
            return;
        }

        let viewport_height = inner_area.height as usize;

        // Ensure selected item is visible
        state.ensure_visible(viewport_height);

        // Build only the rows on screen.
        let start = state.offset;
        let items = self.rows(state, start..start + viewport_height);
        let end = start + items.len();

        // Size bar width. A column narrower than the bar cannot show it, and in
        // that case the row text gets the space back instead of being squeezed
        // into nothing.
        let size_bar_width: u16 = if inner_area.width >= 10 { 10 } else { 0 };
        let size_text_width: u16 = 10;

        for (row_idx, item_idx) in (start..end).enumerate() {
            let item = &items[row_idx];
            let y = inner_area.y + row_idx as u16;
            let is_selected = item_idx == state.selected;
            let is_marked = self.marked.contains(&item.path);

            // Check if item is in clipboard
            let in_clipboard = self.clipboard.paths.contains(&item.path);
            let clipboard_mode = if in_clipboard {
                self.clipboard.mode
            } else {
                ClipboardMode::Empty
            };

            // Build tree prefix
            let mut prefix = String::new();
            for &parent_is_last in &item.parent_last_siblings {
                prefix.push_str(if parent_is_last { "  " } else { "│ " });
            }
            if item.depth > 0 {
                prefix.push_str(if item.is_last_sibling {
                    "└─"
                } else {
                    "├─"
                });
            }

            // Selection/clipboard indicator
            // Priority: marked > cut > copied > none
            let (checkbox, checkbox_style) = if is_marked {
                ("● ", Style::default().fg(self.theme.info))
            } else if clipboard_mode == ClipboardMode::Cut {
                ("✂ ", Style::default().fg(self.theme.warning))
            } else if clipboard_mode == ClipboardMode::Copy {
                ("⎘ ", Style::default().fg(self.theme.success))
            } else {
                ("  ", Style::default().fg(self.theme.muted))
            };
            let checkbox_width: u16 = 2;

            // Expand indicator
            let expand_indicator = match item.node.kind {
                VisibleNodeKind::Directory { expanded } => {
                    if expanded {
                        "▼ "
                    } else {
                        "▶ "
                    }
                }
                _ => "  ",
            };

            // Node style - clipboard items get special styling
            let base_style = match item.node.kind {
                VisibleNodeKind::Directory { .. } => self.theme.directory,
                VisibleNodeKind::File { executable: true } => self.theme.executable,
                VisibleNodeKind::File { executable: false } => self.theme.file,
                VisibleNodeKind::Symlink { broken: true } => {
                    self.theme.symlink.add_modifier(Modifier::DIM)
                }
                VisibleNodeKind::Symlink { broken: false } => self.theme.symlink,
                VisibleNodeKind::Other => self.theme.muted.into(),
            };

            // Apply clipboard styling (cut items are dimmed, copied items are italic)
            let base_style = if clipboard_mode == ClipboardMode::Cut {
                base_style.add_modifier(Modifier::DIM)
            } else if clipboard_mode == ClipboardMode::Copy {
                base_style.add_modifier(Modifier::ITALIC)
            } else {
                base_style
            };

            // Available width for the name, in terminal columns: the guide
            // lines and indicators are multi-byte but one column per char.
            let prefix_width = prefix.width() + checkbox_width as usize + expand_indicator.width();
            let available_for_name = inner_area
                .width
                .saturating_sub(prefix_width as u16)
                .saturating_sub(size_bar_width + 1)
                .saturating_sub(size_text_width + 1);

            // Truncate name if needed (Unicode-safe)
            let name = fit_to_width(&item.node.name, available_for_name as usize);

            // Build line with checkbox
            let prefix_span = Span::styled(&prefix, self.theme.tree_lines);
            let checkbox_span = Span::styled(checkbox, checkbox_style);
            let expand_span = Span::styled(expand_indicator, Style::default().fg(self.theme.muted));
            let name_span = Span::styled(&name, base_style);

            // Git status indicator
            let (git_indicator, git_style) = match item.node.git_status {
                Some(status) if status.is_displayable() => {
                    let color = self.theme.git_status_color(status);
                    (
                        format!(" {}", status.indicator()),
                        Style::default().fg(color),
                    )
                }
                _ => (String::new(), Style::default()),
            };
            let git_span = Span::styled(&git_indicator, git_style);

            // Pad name to fill space (accounting for git indicator)
            // Use display width, not byte length, for correct Unicode padding
            let git_display_width = git_indicator.width() as u16;
            let name_display_width = name.width() as u16;
            let name_padding = " ".repeat(
                available_for_name
                    .saturating_sub(name_display_width)
                    .saturating_sub(git_display_width) as usize,
            );
            let padding_span = Span::raw(&name_padding);

            // Size text - show "..." for directories with unknown size (0 bytes)
            let size_text = if matches!(item.node.kind, VisibleNodeKind::Directory { .. })
                && item.node.size == 0
            {
                format!("{:>10}", "...")
            } else {
                format!("{:>10}", format_size(item.node.size))
            };
            let size_span = Span::styled(&size_text, Style::default().fg(self.theme.muted));

            let line = Line::from(vec![
                prefix_span,
                checkbox_span,
                expand_span,
                name_span,
                git_span,
                padding_span,
                Span::raw(" "),
                size_span,
            ]);

            // Apply selection style (cursor highlight)
            let line = if is_selected {
                line.style(self.theme.selected)
            } else if is_marked {
                // Marked but not selected - subtle highlight
                line.style(Style::default().add_modifier(Modifier::BOLD))
            } else {
                line
            };

            // Render line
            let line_area = Rect::new(
                inner_area.x,
                y,
                inner_area
                    .width
                    .saturating_sub(size_bar_width)
                    .saturating_sub(u16::from(size_bar_width > 0)),
                1,
            );
            Widget::render(line, line_area, buf);

            // Render the size bar hugging the right edge, when there is one.
            if size_bar_width > 0 {
                let ratio = if self.total_size > 0 {
                    item.node.size as f64 / self.total_size as f64
                } else {
                    0.0
                };

                let bar_area = Rect::new(
                    inner_area.x + inner_area.width - size_bar_width,
                    y,
                    size_bar_width,
                    1,
                );

                let bar = CompactSizeBar::new(ratio).style(self.theme.size_bar_style(ratio));
                Widget::render(bar, bar_area, buf);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::{sample_node_tree, sample_root_path};
    use ratatui::buffer::Buffer;

    fn render_at(area: Rect, state: &mut TreeState) -> Buffer {
        let root = sample_node_tree();
        let root_path = sample_root_path();
        let theme = Theme::dark();
        let marked = HashSet::new();
        let clipboard = ClipboardState::default();
        let mut buf = Buffer::empty(area);
        let view = TreeView::new(&root, &root_path, &theme, &marked, &clipboard);
        StatefulWidget::render(view, area, &mut buf, state);
        buf
    }

    fn expanded_state() -> TreeState {
        let mut state = TreeState::new(sample_root_path());
        state.expand(&sample_root_path().join("src"));
        state
    }

    #[test]
    fn flatten_lists_only_expanded_subtrees() {
        let root = sample_node_tree();
        let root_path = sample_root_path();
        let theme = Theme::dark();
        let marked = HashSet::new();
        let clipboard = ClipboardState::default();
        let view = TreeView::new(&root, &root_path, &theme, &marked, &clipboard);

        // Only the root is expanded, so its 7 direct children are visible.
        let collapsed = TreeState::new(root_path.clone());
        let names: Vec<_> = view
            .flatten(&collapsed)
            .into_iter()
            .map(|item| item.node.name)
            .collect();
        assert_eq!(names.len(), 8, "root plus its direct children: {names:?}");
        assert!(!names.contains(&"modified.rs".to_string()));

        // Expanding `src` reveals its children but not `nested`'s.
        let mut state = collapsed.clone();
        state.expand(&root_path.join("src"));
        let names: Vec<_> = view
            .flatten(&state)
            .into_iter()
            .map(|item| item.node.name)
            .collect();
        assert!(names.contains(&"modified.rs".to_string()));
        assert!(!names.contains(&"deep.txt".to_string()));

        state.expand(&root_path.join("src").join("nested"));
        let names: Vec<_> = view
            .flatten(&state)
            .into_iter()
            .map(|item| item.node.name)
            .collect();
        assert!(names.contains(&"deep.txt".to_string()));
    }

    #[test]
    fn flatten_count_matches_flatten_length() {
        let root = sample_node_tree();
        let root_path = sample_root_path();
        let theme = Theme::dark();
        let marked = HashSet::new();
        let clipboard = ClipboardState::default();

        // `flatten_count` exists purely to skip the Vec allocation, so the two
        // must never disagree — the app uses the count to bound navigation
        // against a list produced by `flatten`.
        for state in [TreeState::new(root_path.clone()), expanded_state()] {
            let view = TreeView::new(&root, &root_path, &theme, &marked, &clipboard);
            let counted = view.flatten_count(&state);
            let view = TreeView::new(&root, &root_path, &theme, &marked, &clipboard);
            assert_eq!(counted, view.flatten(&state).len());
        }
    }

    #[test]
    fn every_window_matches_the_same_slice_of_flatten() {
        let root = sample_node_tree();
        let root_path = sample_root_path();
        let theme = Theme::dark();
        let marked = HashSet::new();
        let clipboard = ClipboardState::default();
        let mut state = expanded_state();
        state.expand(&root_path.join("src").join("nested"));
        let view = TreeView::new(&root, &root_path, &theme, &marked, &clipboard);

        // Rows before a window are skipped without being built, which must
        // not shift guide lines, depths or paths of the rows inside it.
        let items = view.flatten(&state);
        for (index, item) in items.iter().enumerate() {
            assert_eq!(view.position(&state, &item.path), Some(index));
        }
        assert_eq!(view.position(&state, &root_path.join("missing")), None);
        let all: Vec<String> = items.iter().map(|item| format!("{item:?}")).collect();
        for start in 0..=all.len() {
            for end in start..=all.len() + 1 {
                let window: Vec<String> = view
                    .rows(&state, start..end)
                    .iter()
                    .map(|item| format!("{item:?}"))
                    .collect();
                assert_eq!(window, all[start..end.min(all.len())], "{start}..{end}");
            }
        }
    }

    #[test]
    fn flatten_builds_paths_by_joining_names() {
        let root = sample_node_tree();
        let root_path = sample_root_path();
        let theme = Theme::dark();
        let marked = HashSet::new();
        let clipboard = ClipboardState::default();
        let mut state = expanded_state();
        state.expand(&root_path.join("src").join("nested"));

        let view = TreeView::new(&root, &root_path, &theme, &marked, &clipboard);
        let items = view.flatten(&state);
        let deep = items
            .iter()
            .find(|item| item.node.name == "deep.txt")
            .expect("deep.txt is visible");
        assert_eq!(deep.path, root_path.join("src/nested/deep.txt"));
        assert_eq!(deep.depth, 3);
    }

    #[test]
    fn toggle_expand_flips_state() {
        let mut state = TreeState::new(sample_root_path());
        let path = sample_root_path().join("src");
        assert!(!state.is_expanded(&path));
        state.toggle_expand(&path);
        assert!(state.is_expanded(&path));
        state.toggle_expand(&path);
        assert!(!state.is_expanded(&path));
    }

    #[test]
    fn ensure_visible_scrolls_the_minimum_distance() {
        let mut state = TreeState::new(sample_root_path());

        // Selection below the viewport scrolls just far enough to show it.
        state.selected = 12;
        state.ensure_visible(10);
        assert_eq!(state.offset, 3);

        // Selection above the viewport scrolls up to sit on the first row.
        state.selected = 1;
        state.ensure_visible(10);
        assert_eq!(state.offset, 1);

        // A selection already inside the viewport does not move the offset.
        state.selected = 5;
        state.ensure_visible(10);
        assert_eq!(state.offset, 1);
    }

    #[test]
    fn navigation_stays_within_bounds() {
        let mut state = TreeState::new(sample_root_path());
        state.move_up(100);
        assert_eq!(state.selected, 0);
        state.move_down(100, 8);
        assert_eq!(state.selected, 7);
        state.jump_to_top();
        assert_eq!(state.selected, 0);
        state.jump_to_bottom(8);
        assert_eq!(state.selected, 7);

        // An empty tree must not underflow.
        state.jump_to_bottom(0);
        assert_eq!(state.selected, 0);
        state.move_down(1, 0);
        assert_eq!(state.selected, 0);
    }

    #[test]
    fn renders_at_every_size_without_panicking() {
        // The size bar is anchored to the right edge; a column narrower than
        // the bar used to compute an out-of-bounds rect and abort the app.
        for width in 1u16..=60 {
            for height in [1u16, 2, 3, 10, 40] {
                let mut state = expanded_state();
                let _ = render_at(Rect::new(0, 0, width, height), &mut state);
            }
        }
    }

    #[test]
    fn renders_at_every_offset_within_a_block() {
        // A non-zero origin is what the app actually passes, and it is what
        // makes right-edge arithmetic easy to get wrong.
        for x in [0u16, 1, 7] {
            for y in [0u16, 1, 5] {
                let area = Rect::new(x, y, 40, 12);
                let mut buf = Buffer::empty(Rect::new(0, 0, 80, 24));
                let root = sample_node_tree();
                let root_path = sample_root_path();
                let theme = Theme::dark();
                let marked = HashSet::new();
                let clipboard = ClipboardState::default();
                let mut state = expanded_state();
                let view = TreeView::new(&root, &root_path, &theme, &marked, &clipboard)
                    .block(Block::default().borders(ratatui::widgets::Borders::ALL));
                StatefulWidget::render(view, area, &mut buf, &mut state);
            }
        }
    }

    #[test]
    fn a_narrow_column_still_renders_rows() {
        // Below the size-bar width the bar is dropped and the row reclaims its
        // columns, so the tree structure stays visible. (The name budget is
        // still spent on the size text first, so names themselves only appear
        // once the column is wide enough for both.)
        let mut state = expanded_state();
        let buf = render_at(Rect::new(0, 0, 9, 10), &mut state);
        let rendered: String = buf.content().iter().map(|cell| cell.symbol()).collect();
        assert!(
            rendered.contains('├') || rendered.contains('└'),
            "narrow render produced no rows at all: {rendered:?}"
        );
    }

    #[test]
    fn a_wide_column_renders_the_size_bar() {
        let mut state = expanded_state();
        let buf = render_at(Rect::new(0, 0, 60, 10), &mut state);
        let rendered: String = buf.content().iter().map(|cell| cell.symbol()).collect();
        assert!(
            rendered.contains("65.5 kB"),
            "expected a formatted size in the row: {rendered:?}"
        );
    }

    #[test]
    fn exactly_one_row_carries_the_selection_highlight() {
        let mut state = expanded_state();
        state.selected = 2;
        let buf = render_at(Rect::new(0, 0, 60, 10), &mut state);
        let selected_bg = Theme::dark()
            .selected
            .bg
            .expect("selection has a background");

        let highlighted: Vec<u16> = (0..10u16)
            .filter(|&y| buf[(0, y)].bg == selected_bg)
            .collect();
        assert_eq!(highlighted, vec![2], "only the selected row is highlighted");
    }
}