tui-widgets: Add tree rendering affordances

df53163a770393f26473d6bb25a7e816ca546c86
Move reusable row styling, visual-depth, width, and viewport helpers
into the TUI widget layer so application trees do not hand-roll those
rendering details.
Alexis Sellier committed ago 1 parent b0ea0c63
crates/tui-core/src/cell.rs +2 -1
221 221
pub(crate) fn char_width(ch: char) -> usize {
222 222
    if ch == '\u{fe0f}' || ch == '\u{fe0e}' || ch.is_control() {
223 223
        0
224 224
    // TODO: Move these glyphs somewhere and make them configurable, or include the
225 225
    // full set of unicode glyphs.
226 -
    } else if matches!(ch, '✓' | '✔' | '🗩') {
226 +
    } else if matches!(ch, '✓' | '✔' | '🗩' | '🞄') {
227 227
        1
228 228
    } else if matches!(
229 229
        ch as u32,
230 230
        0x1100..=0x115f
231 231
            | 0x2329..=0x232a
254 254
    fn test_width() {
255 255
        assert_eq!("abc".width(), 3);
256 256
        assert_eq!("✓".width(), 1);
257 257
        assert_eq!("✔".width(), 1);
258 258
        assert_eq!("🗩".width(), 1);
259 +
        assert_eq!("🞄".width(), 1);
259 260
        assert_eq!("2 ✔ · 4 hunks left".width(), 18);
260 261
        assert_eq!("❤️".width(), 2);
261 262
        assert_eq!("🪵".width(), 2);
262 263
    }
263 264
crates/tui-widgets/src/tree.rs +206 -24
14 14
const INDENT_COLS: usize = 2;
15 15
/// Columns reserved for the branch marker and following space.
16 16
const MARKER_COLS: usize = 2;
17 17
/// Minimum gap between the row label and right-side detail text.
18 18
const DETAIL_GAP_COLS: usize = 2;
19 -
/// Glyph used for expanded branches.
20 -
const EXPANDED_MARKER: char = '▾';
21 -
/// Glyph used for collapsed branches.
22 -
const COLLAPSED_MARKER: char = '▸';
23 -
/// Glyph used for leaves.
24 -
const LEAF_MARKER: char = ' ';
25 19
26 20
/// Caller-owned data adapter for a renderable tree.
27 21
pub trait TreeModel {
28 22
    /// Stable node identifier.
29 23
    type Id: Copy + Ord;
52 46
pub struct TreeRow {
53 47
    /// Main row label.
54 48
    pub label: Line,
55 49
    /// Optional right-aligned row detail.
56 50
    pub detail: Line,
51 +
    /// Marker glyph rendered in the fixed tree marker column.
52 +
    pub marker: Option<char>,
53 +
    /// Style applied to the branch or leaf marker.
54 +
    pub marker_style: Style,
55 +
    /// Full-width row style applied when the row is not selected.
56 +
    pub style: Style,
57 57
}
58 58
59 59
impl TreeRow {
60 60
    /// Creates a row with a label and no detail.
61 61
    pub fn new(label: impl Into<Line>) -> Self {
62 62
        Self {
63 63
            label: label.into(),
64 64
            detail: Line::blank(),
65 +
            marker: None,
66 +
            marker_style: Style::default(),
67 +
            style: Style::default(),
65 68
        }
66 69
    }
67 70
68 71
    /// Sets the right-aligned detail text.
69 72
    pub fn detail(mut self, detail: impl Into<Line>) -> Self {
70 73
        self.detail = detail.into();
71 74
        self
72 75
    }
76 +
77 +
    /// Sets the marker glyph.
78 +
    pub fn marker(mut self, marker: char) -> Self {
79 +
        self.marker = Some(marker);
80 +
        self
81 +
    }
82 +
83 +
    /// Sets the branch or leaf marker style.
84 +
    pub fn marker_style(mut self, style: Style) -> Self {
85 +
        self.marker_style = style;
86 +
        self
87 +
    }
88 +
89 +
    /// Sets the full-width row style.
90 +
    pub fn style(mut self, style: Style) -> Self {
91 +
        self.style = style;
92 +
        self
93 +
    }
94 +
95 +
    /// Returns the columns needed to render this row without truncation.
96 +
    pub fn width(&self) -> usize {
97 +
        let w = self.detail.width();
98 +
        let w = if w == 0 {
99 +
            0
100 +
        } else {
101 +
            w.saturating_add(DETAIL_GAP_COLS)
102 +
        };
103 +
        self.label.width().saturating_add(w)
104 +
    }
73 105
}
74 106
75 107
/// Visual styling for a tree widget.
76 108
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77 109
pub struct TreeStyle {
78 110
    /// Style applied to the selected row while the tree is active.
79 111
    pub selected_active: Style,
80 112
    /// Style applied to the selected row while the tree is inactive.
81 113
    pub selected_inactive: Style,
114 +
    /// Glyph used for expanded branches.
115 +
    pub expanded_marker: char,
116 +
    /// Glyph used for collapsed branches.
117 +
    pub collapsed_marker: char,
118 +
    /// Glyph used for leaves.
119 +
    pub leaf_marker: char,
82 120
}
83 121
84 122
impl TreeStyle {
85 123
    /// Default tree style.
86 124
    pub const DEFAULT: Self = Self {
87 125
        selected_active: Style::new(Color::Unset).bg(Color::Blue),
88 126
        selected_inactive: Style::new(Color::Unset).bg(Color::Fixed(238)),
127 +
        expanded_marker: '▿',
128 +
        collapsed_marker: '▹',
129 +
        leaf_marker: ' ',
89 130
    };
90 131
91 -
    /// Creates a tree style from selected-row styles.
132 +
    /// Creates a tree style from selected-row styles, keeping the default markers.
92 133
    pub const fn new(selected_active: Style, selected_inactive: Style) -> Self {
93 134
        Self {
94 135
            selected_active,
95 136
            selected_inactive,
137 +
            expanded_marker: Self::DEFAULT.expanded_marker,
138 +
            collapsed_marker: Self::DEFAULT.collapsed_marker,
139 +
            leaf_marker: Self::DEFAULT.leaf_marker,
140 +
        }
141 +
    }
142 +
143 +
    /// Returns the marker glyph for a visible node state.
144 +
    pub const fn marker_for(&self, state: TreeNodeState) -> char {
145 +
        match state {
146 +
            TreeNodeState::Leaf => self.leaf_marker,
147 +
            TreeNodeState::Collapsed => self.collapsed_marker,
148 +
            TreeNodeState::Expanded => self.expanded_marker,
96 149
        }
97 150
    }
98 151
}
99 152
100 153
impl Default for TreeStyle {
106 159
/// Expansion and selection state for a tree.
107 160
#[derive(Debug, Clone, Default, PartialEq, Eq)]
108 161
pub struct TreeState<Id> {
109 162
    /// Expanded branch ids.
110 163
    pub expanded: BTreeSet<Id>,
111 -
    /// Selected node id.
164 +
    /// Selected node (cursor).
112 165
    pub selected: Option<Id>,
166 +
    /// Pivot used by range selection.
167 +
    pub anchor: Option<Id>,
113 168
}
114 169
115 170
impl<Id> TreeState<Id>
116 171
where
117 172
    Id: Copy + Ord,
119 174
    /// Creates empty tree state.
120 175
    pub fn new() -> Self {
121 176
        Self {
122 177
            expanded: BTreeSet::new(),
123 178
            selected: None,
179 +
            anchor: None,
124 180
        }
125 181
    }
126 182
127 183
    /// Returns whether `id` is expanded.
128 184
    pub fn is_expanded(&self, id: Id) -> bool {
153 209
            self.expanded.insert(id);
154 210
            Some(TreeNodeState::Expanded)
155 211
        }
156 212
    }
157 213
158 -
    /// Sets the selected node.
214 +
    /// Sets the selected node and resets the anchor to it.
159 215
    pub fn select(&mut self, id: Id) -> bool {
160 216
        let changed = self.selected != Some(id);
161 217
        self.selected = Some(id);
218 +
        self.anchor = Some(id);
162 219
        changed
163 220
    }
164 221
165 -
    /// Clears the selected node.
222 +
    /// Clears the selected node and the anchor.
166 223
    pub fn clear_selection(&mut self) -> bool {
224 +
        self.anchor = None;
167 225
        self.selected.take().is_some()
168 226
    }
169 227
170 228
    /// Returns the selected node.
171 229
    pub const fn selected(&self) -> Option<Id> {
172 230
        self.selected
173 231
    }
174 232
233 +
    /// Returns the anchor node.
234 +
    pub const fn anchor(&self) -> Option<Id> {
235 +
        self.anchor
236 +
    }
237 +
238 +
    /// Sets the anchor without changing the selection.
239 +
    pub fn set_anchor(&mut self, id: Option<Id>) {
240 +
        self.anchor = id;
241 +
    }
242 +
175 243
    /// Selects the zero-based visible node.
176 244
    pub fn select_nth<M>(&mut self, model: &M, index: usize) -> bool
177 245
    where
178 246
        M: TreeModel<Id = Id>,
179 247
    {
203 271
            index.saturating_add(delta as usize).min(rows.len() - 1)
204 272
        };
205 273
        self.select(rows[next].id)
206 274
    }
207 275
276 +
    /// Moves selection by `delta` and returns the ids between the anchor and the
277 +
    /// new selection in visible-row order, inclusive on both ends.
278 +
    ///
279 +
    /// The anchor is preserved across calls so successive extends grow or shrink
280 +
    /// the same range. If the anchor is unset or no longer visible, it is reset
281 +
    /// to the new cursor and a single-element range is returned.
282 +
    pub fn extend_selection<M>(&mut self, model: &M, delta: isize) -> Vec<Id>
283 +
    where
284 +
        M: TreeModel<Id = Id>,
285 +
    {
286 +
        let rows = Tree::new(model, self).visible_rows();
287 +
        if rows.is_empty() {
288 +
            self.clear_selection();
289 +
            return Vec::new();
290 +
        }
291 +
        let index = self
292 +
            .selected
293 +
            .and_then(|id| rows.iter().position(|row| row.id == id))
294 +
            .unwrap_or(0);
295 +
296 +
        let next = if delta.is_negative() {
297 +
            index.saturating_sub(delta.unsigned_abs())
298 +
        } else {
299 +
            index.saturating_add(delta as usize).min(rows.len() - 1)
300 +
        };
301 +
        self.selected = Some(rows[next].id);
302 +
303 +
        let anchor_idx = self
304 +
            .anchor
305 +
            .and_then(|id| rows.iter().position(|row| row.id == id))
306 +
            .unwrap_or(next);
307 +
        self.anchor = Some(rows[anchor_idx].id);
308 +
309 +
        let (lo, hi) = if anchor_idx <= next {
310 +
            (anchor_idx, next)
311 +
        } else {
312 +
            (next, anchor_idx)
313 +
        };
314 +
        rows[lo..=hi].iter().map(|row| row.id).collect()
315 +
    }
316 +
208 317
    /// Toggles the selected branch if a branch is selected.
209 318
    pub fn toggle_selected<M>(&mut self, model: &M) -> Option<TreeNodeState>
210 319
    where
211 320
        M: TreeModel<Id = Id>,
212 321
    {
224 333
    Collapsed,
225 334
    /// Branch is expanded.
226 335
    Expanded,
227 336
}
228 337
229 -
impl TreeNodeState {
230 -
    /// Returns the marker glyph for this state.
231 -
    pub const fn marker(self) -> char {
232 -
        match self {
233 -
            TreeNodeState::Leaf => LEAF_MARKER,
234 -
            TreeNodeState::Collapsed => COLLAPSED_MARKER,
235 -
            TreeNodeState::Expanded => EXPANDED_MARKER,
236 -
        }
237 -
    }
238 -
}
239 -
240 338
/// One rendered row in tree order before terminal-width layout.
241 339
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
242 340
pub struct TreeVisibleRow<Id> {
243 341
    /// Node id for this row.
244 342
    pub id: Id,
300 398
    pub const fn style(mut self, style: TreeStyle) -> Self {
301 399
        self.style = style;
302 400
        self
303 401
    }
304 402
403 +
    /// Returns columns needed to render any tree row without truncation.
404 +
    pub fn content_cols(&self, minimum: usize) -> usize {
405 +
        let mut cols = minimum;
406 +
407 +
        self.walk(|row| {
408 +
            let prefix_cols = row
409 +
                .depth
410 +
                .saturating_mul(INDENT_COLS)
411 +
                .saturating_add(MARKER_COLS);
412 +
            cols = cols.max(prefix_cols.saturating_add(self.model.row(row.id).width()));
413 +
            true
414 +
        });
415 +
        cols
416 +
    }
417 +
418 +
    /// Returns the visible index of the selected row.
419 +
    pub fn selected_row(&self, rows: &[TreeVisibleRow<M::Id>]) -> Option<usize> {
420 +
        let selected = self.state.selected?;
421 +
422 +
        rows.iter().position(|row| row.id == selected)
423 +
    }
424 +
305 425
    /// Walks tree rows in render order.
306 426
    fn walk(&self, mut visit: impl FnMut(TreeVisibleRow<M::Id>) -> bool) {
307 427
        let roots = self.model.roots();
308 428
        let mut stack = Vec::with_capacity(roots.len());
309 429
        stack.extend(roots.iter().rev().map(|&id| (id, 0)));
359 479
        let mut line = Line::blank();
360 480
361 481
        if indent_cols > 0 {
362 482
            line.push(Label::from(" ".repeat(indent_cols)));
363 483
        }
364 -
        line.push(Label::from_char(visible.state.marker()));
484 +
        let marker = row
485 +
            .marker
486 +
            .unwrap_or_else(|| self.style.marker_for(visible.state));
487 +
        line.push(Label::from_char(marker).style(row.marker_style));
365 488
        line.push(Label::space());
366 489
367 490
        if prefix_cols < cols {
368 491
            let detail_width = row.detail.width();
369 492
            let detail_fits = detail_width > 0
382 505
                line = line.extend(row.label.truncated(cols - prefix_cols, "…"));
383 506
            }
384 507
        }
385 508
386 509
        let line = line.truncated(cols, "…");
387 -
        if self.state.selected == Some(visible.id) {
388 -
            let style = if self.active {
510 +
        let style = if self.state.selected == Some(visible.id) {
511 +
            let selected = if self.active {
389 512
                self.style.selected_active
390 513
            } else {
391 514
                self.style.selected_inactive
392 515
            };
516 +
            selected.merge(row.style)
517 +
        } else {
518 +
            row.style
519 +
        };
520 +
521 +
        if style != Style::default() {
393 522
            return line.style(style).padded(cols);
394 523
        }
395 524
        line
396 525
    }
397 526
}
607 736
        assert_eq!(state.selected(), Some(README));
608 737
        assert!(state.select_next(&model, -99));
609 738
        assert_eq!(state.selected(), Some(SRC));
610 739
    }
611 740
741 +
    #[test]
742 +
    fn select_tracks_anchor_with_cursor() {
743 +
        let model = Model::sample();
744 +
        let mut state = TreeState::new();
745 +
746 +
        state.expand(SRC);
747 +
        state.select(WIDGETS);
748 +
        assert_eq!(state.anchor(), Some(WIDGETS));
749 +
        state.select_next(&model, -1);
750 +
        assert_eq!(state.anchor(), state.selected());
751 +
        state.clear_selection();
752 +
        assert_eq!(state.anchor(), None);
753 +
    }
754 +
755 +
    #[test]
756 +
    fn extend_selection_returns_range_in_visible_order() {
757 +
        let model = Model::sample();
758 +
        let mut state = TreeState::new();
759 +
760 +
        state.expand(SRC);
761 +
        state.select(SRC);
762 +
763 +
        let down = state.extend_selection(&model, 2);
764 +
        assert_eq!(down, vec![SRC, LIB, WIDGETS]);
765 +
        assert_eq!(state.anchor(), Some(SRC));
766 +
        assert_eq!(state.selected(), Some(WIDGETS));
767 +
768 +
        let shrink = state.extend_selection(&model, -1);
769 +
        assert_eq!(shrink, vec![SRC, LIB]);
770 +
        assert_eq!(state.anchor(), Some(SRC));
771 +
        assert_eq!(state.selected(), Some(LIB));
772 +
773 +
        let across = state.extend_selection(&model, 3);
774 +
        assert_eq!(across, vec![SRC, LIB, WIDGETS, README]);
775 +
        assert_eq!(state.anchor(), Some(SRC));
776 +
        assert_eq!(state.selected(), Some(README));
777 +
    }
778 +
779 +
    #[test]
780 +
    fn extend_selection_resets_anchor_when_anchor_not_visible() {
781 +
        let model = Model::sample();
782 +
        let mut state = TreeState::new();
783 +
784 +
        state.expand(SRC);
785 +
        state.select(LIB);
786 +
        // Anchor LIB is hidden after src collapses.
787 +
        state.collapse(SRC);
788 +
789 +
        let range = state.extend_selection(&model, 1);
790 +
        assert_eq!(range.len(), 1);
791 +
        assert_eq!(state.anchor(), state.selected());
792 +
    }
793 +
612 794
    #[test]
613 795
    fn toggling_selected_branch_changes_visible_rows() {
614 796
        let model = Model::sample();
615 797
        let mut state = TreeState::new();
616 798
crates/tui-widgets/src/viewport.rs +50 -0
215 215
            .min(self.content_rows);
216 216
217 217
        self.offset..end
218 218
    }
219 219
220 +
    /// Returns a view scrolled to make a content row visible.
221 +
    pub fn with_row_visible(self, row: usize, placement: Placement) -> Self {
222 +
        let mut viewport = Viewport::from_offset(self.offset);
223 +
224 +
        viewport.scroll_to_row(row, self.content_rows, self.visible_rows, placement);
225 +
        viewport.view(self.content_rows, self.visible_rows)
226 +
    }
227 +
220 228
    /// Returns the local row for a content row.
221 229
    pub fn project(self, content_row: usize) -> Option<usize> {
222 230
        self.range()
223 231
            .contains(&content_row)
224 232
            .then(|| content_row - self.offset)
247 255
            .skip(range.start)
248 256
            .take(range.end.saturating_sub(range.start));
249 257
250 258
        Line::renders(visible.cloned(), area, buf);
251 259
    }
260 +
261 +
    /// Renders visible rows from an on-demand line producer.
262 +
    pub fn render_rows(
263 +
        self,
264 +
        area: Rect,
265 +
        buf: &mut Buffer,
266 +
        mut line: impl FnMut(usize, usize) -> Line,
267 +
    ) {
268 +
        let lines = self.range().map(|row| line(row, area.cols));
269 +
270 +
        Line::renders(lines, area, buf);
271 +
    }
252 272
}
253 273
254 274
/// Returns the largest valid scroll offset.
255 275
pub const fn max_offset(content_rows: usize, visible_rows: usize) -> usize {
256 276
    content_rows.saturating_sub(visible_rows)
423 443
        View::new(1, 4, 2).render_lines(&lines, buffer.area(), &mut buffer);
424 444
425 445
        assert_eq!(buffer.lines(), vec!["one  ", "two  "]);
426 446
    }
427 447
448 +
    #[test]
449 +
    fn with_row_visible_scrolls_like_viewport() {
450 +
        assert_eq!(
451 +
            View::new(0, 10, 3)
452 +
                .with_row_visible(5, Placement::Minimal)
453 +
                .offset,
454 +
            3
455 +
        );
456 +
        assert_eq!(
457 +
            View::new(4, 10, 3)
458 +
                .with_row_visible(5, Placement::Minimal)
459 +
                .offset,
460 +
            4
461 +
        );
462 +
    }
463 +
464 +
    #[test]
465 +
    fn render_rows_projects_visible_content() {
466 +
        let mut rendered = Vec::new();
467 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 2));
468 +
469 +
        View::new(2, 5, 2).render_rows(buffer.area(), &mut buffer, |row, cols| {
470 +
            rendered.push(row);
471 +
            Line::new(format!("{row}:{cols}"))
472 +
        });
473 +
474 +
        assert_eq!(rendered, vec![2, 3]);
475 +
        assert_eq!(buffer.lines(), vec!["2:5  ", "3:5  "]);
476 +
    }
477 +
428 478
    #[test]
429 479
    fn rendered_view_keeps_only_visible_rows() {
430 480
        let lines = ["a", "b", "c"]
431 481
            .into_iter()
432 482
            .map(Line::new)
crates/tui-widgets/tests/golden/tree_rows_16x3.txt +2 -2
1 -
▾ src        ***
1 +
▿ src        ***
2 2
    lib.rs     *
3 -
  ▸ widgets
3 +
  ▹ widgets
crates/tui-widgets/tests/golden/tree_scroll_22x2.txt +1 -1
1 -
  ▾ widgets          ┃
1 +
  ▿ widgets          ┃
2 2
      tree.rs     ***│
crates/tui-widgets/tests/golden/tree_selected_14x2.txt +1 -1
1 -
▸ src      ***
1 +
▹ src      ***
2 2
  README.md