tui-widgets: Implement new tree widget
21a7d2f80bf7db614734eb86dbbf24e35ced681e
1 parent
48d993e3
crates/tui-widgets/Cargo.toml
+4 -0
| 10 | 10 | [dependencies] |
|
| 11 | 11 | rustik-tui-core = { workspace = true } |
|
| 12 | 12 | ||
| 13 | 13 | [lints] |
|
| 14 | 14 | workspace = true |
|
| 15 | + | ||
| 16 | + | [[bench]] |
|
| 17 | + | name = "tree" |
|
| 18 | + | harness = false |
crates/tui-widgets/benches/tree.rs
added
+161 -0
| 1 | + | //! Render benchmark for the generic tree widget. |
|
| 2 | + | //! |
|
| 3 | + | //! The harness builds a deterministic tree, expands every branch, and renders a |
|
| 4 | + | //! moving visible window. |
|
| 5 | + | ||
| 6 | + | use std::env; |
|
| 7 | + | use std::time::Instant; |
|
| 8 | + | ||
| 9 | + | use rustik_tui_core::{Buffer, Rect, Widget}; |
|
| 10 | + | use rustik_tui_widgets::{ScrollView, Tree, TreeModel, TreeNodeKind, TreeRow, TreeState}; |
|
| 11 | + | ||
| 12 | + | /// Benchmark frame area. |
|
| 13 | + | const AREA: Rect = Rect::new(0, 0, 120, 40); |
|
| 14 | + | /// Default number of frames to render. |
|
| 15 | + | const DEFAULT_FRAMES: usize = 2_000; |
|
| 16 | + | /// Number of root nodes in the synthetic tree. |
|
| 17 | + | const ROOTS: usize = 64; |
|
| 18 | + | /// Number of directories below each root. |
|
| 19 | + | const DIRS_PER_ROOT: usize = 12; |
|
| 20 | + | /// Number of files below each directory. |
|
| 21 | + | const FILES_PER_DIR: usize = 16; |
|
| 22 | + | ||
| 23 | + | /// Benchmark tree node. |
|
| 24 | + | #[derive(Debug, Clone)] |
|
| 25 | + | struct Node { |
|
| 26 | + | /// Rendered node name. |
|
| 27 | + | name: String, |
|
| 28 | + | /// Optional row detail. |
|
| 29 | + | detail: String, |
|
| 30 | + | /// Child node ids. |
|
| 31 | + | children: Vec<usize>, |
|
| 32 | + | } |
|
| 33 | + | ||
| 34 | + | /// Benchmark tree model. |
|
| 35 | + | #[derive(Debug, Clone)] |
|
| 36 | + | struct Model { |
|
| 37 | + | /// Root node ids. |
|
| 38 | + | roots: Vec<usize>, |
|
| 39 | + | /// Tree nodes indexed by id. |
|
| 40 | + | nodes: Vec<Node>, |
|
| 41 | + | } |
|
| 42 | + | ||
| 43 | + | impl Model { |
|
| 44 | + | /// Creates the deterministic benchmark tree. |
|
| 45 | + | fn new() -> Self { |
|
| 46 | + | let mut roots = Vec::with_capacity(ROOTS); |
|
| 47 | + | let mut nodes = Vec::with_capacity(ROOTS * (1 + DIRS_PER_ROOT * (1 + FILES_PER_DIR))); |
|
| 48 | + | ||
| 49 | + | for root in 0..ROOTS { |
|
| 50 | + | let root_id = nodes.len(); |
|
| 51 | + | roots.push(root_id); |
|
| 52 | + | nodes.push(Node { |
|
| 53 | + | name: format!("crate-{root:03}"), |
|
| 54 | + | detail: format!("{} files", DIRS_PER_ROOT * FILES_PER_DIR), |
|
| 55 | + | children: Vec::with_capacity(DIRS_PER_ROOT), |
|
| 56 | + | }); |
|
| 57 | + | ||
| 58 | + | for dir in 0..DIRS_PER_ROOT { |
|
| 59 | + | let dir_id = nodes.len(); |
|
| 60 | + | nodes[root_id].children.push(dir_id); |
|
| 61 | + | nodes.push(Node { |
|
| 62 | + | name: format!("module-{dir:02}"), |
|
| 63 | + | detail: String::new(), |
|
| 64 | + | children: Vec::with_capacity(FILES_PER_DIR), |
|
| 65 | + | }); |
|
| 66 | + | ||
| 67 | + | for file in 0..FILES_PER_DIR { |
|
| 68 | + | let file_id = nodes.len(); |
|
| 69 | + | nodes[dir_id].children.push(file_id); |
|
| 70 | + | nodes.push(Node { |
|
| 71 | + | name: format!("file_{root:03}_{dir:02}_{file:02}.rs"), |
|
| 72 | + | detail: format!("+{} -{}", file % 17, (root + dir + file) % 9), |
|
| 73 | + | children: Vec::new(), |
|
| 74 | + | }); |
|
| 75 | + | } |
|
| 76 | + | } |
|
| 77 | + | } |
|
| 78 | + | Self { roots, nodes } |
|
| 79 | + | } |
|
| 80 | + | ||
| 81 | + | /// Expands every branch in the model. |
|
| 82 | + | fn expanded_state(&self) -> TreeState<usize> { |
|
| 83 | + | let mut state = TreeState::new(); |
|
| 84 | + | ||
| 85 | + | for (id, node) in self.nodes.iter().enumerate() { |
|
| 86 | + | if !node.children.is_empty() { |
|
| 87 | + | state.expand(id); |
|
| 88 | + | } |
|
| 89 | + | } |
|
| 90 | + | state |
|
| 91 | + | } |
|
| 92 | + | } |
|
| 93 | + | ||
| 94 | + | impl TreeModel for Model { |
|
| 95 | + | type Id = usize; |
|
| 96 | + | ||
| 97 | + | fn roots(&self) -> &[Self::Id] { |
|
| 98 | + | &self.roots |
|
| 99 | + | } |
|
| 100 | + | ||
| 101 | + | fn children(&self, id: Self::Id) -> &[Self::Id] { |
|
| 102 | + | &self.nodes[id].children |
|
| 103 | + | } |
|
| 104 | + | ||
| 105 | + | fn kind(&self, id: Self::Id) -> TreeNodeKind { |
|
| 106 | + | if self.nodes[id].children.is_empty() { |
|
| 107 | + | TreeNodeKind::Leaf |
|
| 108 | + | } else { |
|
| 109 | + | TreeNodeKind::Branch |
|
| 110 | + | } |
|
| 111 | + | } |
|
| 112 | + | ||
| 113 | + | fn row(&self, id: Self::Id) -> TreeRow { |
|
| 114 | + | TreeRow::new(self.nodes[id].name.clone()).detail(self.nodes[id].detail.clone()) |
|
| 115 | + | } |
|
| 116 | + | } |
|
| 117 | + | ||
| 118 | + | /// Parses benchmark arguments. |
|
| 119 | + | fn args() -> usize { |
|
| 120 | + | let mut frames = DEFAULT_FRAMES; |
|
| 121 | + | let mut raw = env::args().skip(1); |
|
| 122 | + | ||
| 123 | + | while let Some(arg) = raw.next() { |
|
| 124 | + | if arg == "--frames" |
|
| 125 | + | && let Some(value) = raw.next() |
|
| 126 | + | && let Ok(parsed) = value.parse() |
|
| 127 | + | { |
|
| 128 | + | frames = parsed; |
|
| 129 | + | } |
|
| 130 | + | } |
|
| 131 | + | frames |
|
| 132 | + | } |
|
| 133 | + | ||
| 134 | + | /// Runs the tree render benchmark. |
|
| 135 | + | fn main() { |
|
| 136 | + | let frames = args(); |
|
| 137 | + | let model = Model::new(); |
|
| 138 | + | let state = model.expanded_state(); |
|
| 139 | + | let tree = Tree::new(&model, &state); |
|
| 140 | + | let rows = tree.visible_rows(); |
|
| 141 | + | let scroll_limit = rows.len().saturating_sub(AREA.rows).max(1); |
|
| 142 | + | let mut buffer = Buffer::empty(AREA); |
|
| 143 | + | let start = Instant::now(); |
|
| 144 | + | ||
| 145 | + | for frame in 0..frames { |
|
| 146 | + | let offset = frame.wrapping_mul(7) % scroll_limit; |
|
| 147 | + | let mut view = ScrollView::virtualized(rows.len(), offset, |row, cols| { |
|
| 148 | + | tree.render_row(rows[row], cols) |
|
| 149 | + | }); |
|
| 150 | + | ||
| 151 | + | view.render(AREA, &mut buffer); |
|
| 152 | + | } |
|
| 153 | + | let elapsed = start.elapsed(); |
|
| 154 | + | let fps = frames as f64 / elapsed.as_secs_f64(); |
|
| 155 | + | ||
| 156 | + | println!("tree benchmark"); |
|
| 157 | + | println!("frames: {frames}"); |
|
| 158 | + | println!("rows: {}", rows.len()); |
|
| 159 | + | println!("elapsed: {:.3}s", elapsed.as_secs_f64()); |
|
| 160 | + | println!("fps: {fps:.1}"); |
|
| 161 | + | } |
crates/tui-widgets/src/lib.rs
+5 -0
| 13 | 13 | pub mod list; |
|
| 14 | 14 | /// Scrollbar rendering. |
|
| 15 | 15 | pub mod scrollbar; |
|
| 16 | 16 | /// Scrollable line widget. |
|
| 17 | 17 | pub mod scrollview; |
|
| 18 | + | /// Generic tree widget. |
|
| 19 | + | pub mod tree; |
|
| 18 | 20 | /// Scroll viewport primitives. |
|
| 19 | 21 | pub mod viewport; |
|
| 20 | 22 | ||
| 21 | 23 | pub use list::{List, Selection}; |
|
| 22 | 24 | pub use scrollbar::{Scrollbar, ScrollbarStyle}; |
|
| 23 | 25 | pub use scrollview::{ScrollLayout, ScrollMetrics, ScrollView, VirtualScrollView, scroll_layout}; |
|
| 26 | + | pub use tree::{ |
|
| 27 | + | Tree, TreeModel, TreeNodeKind, TreeNodeState, TreeRow, TreeState, TreeStyle, TreeVisibleRow, |
|
| 28 | + | }; |
|
| 24 | 29 | pub use viewport::{Placement, Scroll, View, Viewport}; |
crates/tui-widgets/src/tree.rs
added
+692 -0
| 1 | + | //! Generic collapsible tree widget. |
|
| 2 | + | //! |
|
| 3 | + | //! `Tree` renders caller-owned hierarchical data through [`TreeModel`]. The |
|
| 4 | + | //! widget does not perform filesystem access or own loading policy; callers can |
|
| 5 | + | //! adapt a cached file-system arena, package graph, outline, or any other tree |
|
| 6 | + | //! into the small model trait. |
|
| 7 | + | ||
| 8 | + | use std::collections::BTreeSet; |
|
| 9 | + | use std::fmt; |
|
| 10 | + | ||
| 11 | + | use rustik_tui_core::{Buffer, Color, Constraint, Label, Line, Rect, Size, Style, Widget}; |
|
| 12 | + | ||
| 13 | + | /// Columns added for each tree depth. |
|
| 14 | + | const INDENT_COLS: usize = 2; |
|
| 15 | + | /// Columns reserved for the branch marker and following space. |
|
| 16 | + | const MARKER_COLS: usize = 2; |
|
| 17 | + | /// Minimum gap between the row label and right-side detail text. |
|
| 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 | + | ||
| 26 | + | /// Caller-owned data adapter for a renderable tree. |
|
| 27 | + | pub trait TreeModel { |
|
| 28 | + | /// Stable node identifier. |
|
| 29 | + | type Id: Copy + Ord; |
|
| 30 | + | ||
| 31 | + | /// Returns the root node ids in render order. |
|
| 32 | + | fn roots(&self) -> &[Self::Id]; |
|
| 33 | + | /// Returns child node ids for `id` in render order. |
|
| 34 | + | fn children(&self, id: Self::Id) -> &[Self::Id]; |
|
| 35 | + | /// Returns whether `id` is a branch or leaf. |
|
| 36 | + | fn kind(&self, id: Self::Id) -> TreeNodeKind; |
|
| 37 | + | /// Returns the row content for `id`. |
|
| 38 | + | fn row(&self, id: Self::Id) -> TreeRow; |
|
| 39 | + | } |
|
| 40 | + | ||
| 41 | + | /// Structural role of a tree node. |
|
| 42 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
|
| 43 | + | pub enum TreeNodeKind { |
|
| 44 | + | /// Node with collapsible children. |
|
| 45 | + | Branch, |
|
| 46 | + | /// Node without collapsible children. |
|
| 47 | + | Leaf, |
|
| 48 | + | } |
|
| 49 | + | ||
| 50 | + | /// Render content for one tree row. |
|
| 51 | + | #[derive(Debug, Clone, Default)] |
|
| 52 | + | pub struct TreeRow { |
|
| 53 | + | /// Main row label. |
|
| 54 | + | pub label: Line, |
|
| 55 | + | /// Optional right-aligned row detail. |
|
| 56 | + | pub detail: Line, |
|
| 57 | + | } |
|
| 58 | + | ||
| 59 | + | impl TreeRow { |
|
| 60 | + | /// Creates a row with a label and no detail. |
|
| 61 | + | pub fn new(label: impl Into<Line>) -> Self { |
|
| 62 | + | Self { |
|
| 63 | + | label: label.into(), |
|
| 64 | + | detail: Line::blank(), |
|
| 65 | + | } |
|
| 66 | + | } |
|
| 67 | + | ||
| 68 | + | /// Sets the right-aligned detail text. |
|
| 69 | + | pub fn detail(mut self, detail: impl Into<Line>) -> Self { |
|
| 70 | + | self.detail = detail.into(); |
|
| 71 | + | self |
|
| 72 | + | } |
|
| 73 | + | } |
|
| 74 | + | ||
| 75 | + | /// Visual styling for a tree widget. |
|
| 76 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
|
| 77 | + | pub struct TreeStyle { |
|
| 78 | + | /// Style applied to the selected row while the tree is active. |
|
| 79 | + | pub selected_active: Style, |
|
| 80 | + | /// Style applied to the selected row while the tree is inactive. |
|
| 81 | + | pub selected_inactive: Style, |
|
| 82 | + | } |
|
| 83 | + | ||
| 84 | + | impl TreeStyle { |
|
| 85 | + | /// Default tree style. |
|
| 86 | + | pub const DEFAULT: Self = Self { |
|
| 87 | + | selected_active: Style::new(Color::Unset).bg(Color::Blue), |
|
| 88 | + | selected_inactive: Style::new(Color::Unset).bg(Color::Fixed(238)), |
|
| 89 | + | }; |
|
| 90 | + | ||
| 91 | + | /// Creates a tree style from selected-row styles. |
|
| 92 | + | pub const fn new(selected_active: Style, selected_inactive: Style) -> Self { |
|
| 93 | + | Self { |
|
| 94 | + | selected_active, |
|
| 95 | + | selected_inactive, |
|
| 96 | + | } |
|
| 97 | + | } |
|
| 98 | + | } |
|
| 99 | + | ||
| 100 | + | impl Default for TreeStyle { |
|
| 101 | + | fn default() -> Self { |
|
| 102 | + | Self::DEFAULT |
|
| 103 | + | } |
|
| 104 | + | } |
|
| 105 | + | ||
| 106 | + | /// Expansion and selection state for a tree. |
|
| 107 | + | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
|
| 108 | + | pub struct TreeState<Id> { |
|
| 109 | + | /// Expanded branch ids. |
|
| 110 | + | pub expanded: BTreeSet<Id>, |
|
| 111 | + | /// Selected node id. |
|
| 112 | + | pub selected: Option<Id>, |
|
| 113 | + | } |
|
| 114 | + | ||
| 115 | + | impl<Id> TreeState<Id> |
|
| 116 | + | where |
|
| 117 | + | Id: Copy + Ord, |
|
| 118 | + | { |
|
| 119 | + | /// Creates empty tree state. |
|
| 120 | + | pub fn new() -> Self { |
|
| 121 | + | Self { |
|
| 122 | + | expanded: BTreeSet::new(), |
|
| 123 | + | selected: None, |
|
| 124 | + | } |
|
| 125 | + | } |
|
| 126 | + | ||
| 127 | + | /// Returns whether `id` is expanded. |
|
| 128 | + | pub fn is_expanded(&self, id: Id) -> bool { |
|
| 129 | + | self.expanded.contains(&id) |
|
| 130 | + | } |
|
| 131 | + | ||
| 132 | + | /// Expands `id` and returns whether the state changed. |
|
| 133 | + | pub fn expand(&mut self, id: Id) -> bool { |
|
| 134 | + | self.expanded.insert(id) |
|
| 135 | + | } |
|
| 136 | + | ||
| 137 | + | /// Collapses `id` and returns whether the state changed. |
|
| 138 | + | pub fn collapse(&mut self, id: Id) -> bool { |
|
| 139 | + | self.expanded.remove(&id) |
|
| 140 | + | } |
|
| 141 | + | ||
| 142 | + | /// Toggles `id` if it is a branch and returns whether it is expanded afterward. |
|
| 143 | + | pub fn toggle<M>(&mut self, model: &M, id: Id) -> Option<TreeNodeState> |
|
| 144 | + | where |
|
| 145 | + | M: TreeModel<Id = Id>, |
|
| 146 | + | { |
|
| 147 | + | if model.kind(id) == TreeNodeKind::Leaf { |
|
| 148 | + | return None; |
|
| 149 | + | } |
|
| 150 | + | if self.expanded.remove(&id) { |
|
| 151 | + | Some(TreeNodeState::Collapsed) |
|
| 152 | + | } else { |
|
| 153 | + | self.expanded.insert(id); |
|
| 154 | + | Some(TreeNodeState::Expanded) |
|
| 155 | + | } |
|
| 156 | + | } |
|
| 157 | + | ||
| 158 | + | /// Sets the selected node. |
|
| 159 | + | pub fn select(&mut self, id: Id) -> bool { |
|
| 160 | + | let changed = self.selected != Some(id); |
|
| 161 | + | self.selected = Some(id); |
|
| 162 | + | changed |
|
| 163 | + | } |
|
| 164 | + | ||
| 165 | + | /// Clears the selected node. |
|
| 166 | + | pub fn clear_selection(&mut self) -> bool { |
|
| 167 | + | self.selected.take().is_some() |
|
| 168 | + | } |
|
| 169 | + | ||
| 170 | + | /// Returns the selected node. |
|
| 171 | + | pub const fn selected(&self) -> Option<Id> { |
|
| 172 | + | self.selected |
|
| 173 | + | } |
|
| 174 | + | ||
| 175 | + | /// Selects the zero-based visible node. |
|
| 176 | + | pub fn select_nth<M>(&mut self, model: &M, index: usize) -> bool |
|
| 177 | + | where |
|
| 178 | + | M: TreeModel<Id = Id>, |
|
| 179 | + | { |
|
| 180 | + | let row = Tree::new(model, self).visible_rows().get(index).copied(); |
|
| 181 | + | let Some(row) = row else { |
|
| 182 | + | return self.clear_selection(); |
|
| 183 | + | }; |
|
| 184 | + | self.select(row.id) |
|
| 185 | + | } |
|
| 186 | + | ||
| 187 | + | /// Moves selection by `delta` visible rows. |
|
| 188 | + | pub fn select_next<M>(&mut self, model: &M, delta: isize) -> bool |
|
| 189 | + | where |
|
| 190 | + | M: TreeModel<Id = Id>, |
|
| 191 | + | { |
|
| 192 | + | let rows = Tree::new(model, self).visible_rows(); |
|
| 193 | + | if rows.is_empty() { |
|
| 194 | + | return self.clear_selection(); |
|
| 195 | + | } |
|
| 196 | + | let index = self |
|
| 197 | + | .selected |
|
| 198 | + | .and_then(|id| rows.iter().position(|row| row.id == id)) |
|
| 199 | + | .unwrap_or(0); |
|
| 200 | + | let next = if delta.is_negative() { |
|
| 201 | + | index.saturating_sub(delta.unsigned_abs()) |
|
| 202 | + | } else { |
|
| 203 | + | index.saturating_add(delta as usize).min(rows.len() - 1) |
|
| 204 | + | }; |
|
| 205 | + | self.select(rows[next].id) |
|
| 206 | + | } |
|
| 207 | + | ||
| 208 | + | /// Toggles the selected branch if a branch is selected. |
|
| 209 | + | pub fn toggle_selected<M>(&mut self, model: &M) -> Option<TreeNodeState> |
|
| 210 | + | where |
|
| 211 | + | M: TreeModel<Id = Id>, |
|
| 212 | + | { |
|
| 213 | + | self.selected |
|
| 214 | + | .and_then(|selected| self.toggle(model, selected)) |
|
| 215 | + | } |
|
| 216 | + | } |
|
| 217 | + | ||
| 218 | + | /// Render state of a visible tree node. |
|
| 219 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
|
| 220 | + | pub enum TreeNodeState { |
|
| 221 | + | /// Node has no collapsible children. |
|
| 222 | + | Leaf, |
|
| 223 | + | /// Branch is collapsed. |
|
| 224 | + | Collapsed, |
|
| 225 | + | /// Branch is expanded. |
|
| 226 | + | Expanded, |
|
| 227 | + | } |
|
| 228 | + | ||
| 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 | + | /// One rendered row in tree order before terminal-width layout. |
|
| 241 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
|
| 242 | + | pub struct TreeVisibleRow<Id> { |
|
| 243 | + | /// Node id for this row. |
|
| 244 | + | pub id: Id, |
|
| 245 | + | /// Zero-based tree depth. |
|
| 246 | + | pub depth: usize, |
|
| 247 | + | /// Visible expansion state. |
|
| 248 | + | pub state: TreeNodeState, |
|
| 249 | + | } |
|
| 250 | + | ||
| 251 | + | /// Generic tree widget over caller-owned data. |
|
| 252 | + | #[derive(Clone)] |
|
| 253 | + | pub struct Tree<'a, M> |
|
| 254 | + | where |
|
| 255 | + | M: TreeModel, |
|
| 256 | + | { |
|
| 257 | + | /// Tree data model. |
|
| 258 | + | model: &'a M, |
|
| 259 | + | /// Expansion and selection state. |
|
| 260 | + | state: &'a TreeState<M::Id>, |
|
| 261 | + | /// Whether the tree has active focus. |
|
| 262 | + | active: bool, |
|
| 263 | + | /// Tree styling. |
|
| 264 | + | style: TreeStyle, |
|
| 265 | + | } |
|
| 266 | + | ||
| 267 | + | impl<M> fmt::Debug for Tree<'_, M> |
|
| 268 | + | where |
|
| 269 | + | M: TreeModel, |
|
| 270 | + | { |
|
| 271 | + | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
|
| 272 | + | f.debug_struct("Tree") |
|
| 273 | + | .field("active", &self.active) |
|
| 274 | + | .field("style", &self.style) |
|
| 275 | + | .finish_non_exhaustive() |
|
| 276 | + | } |
|
| 277 | + | } |
|
| 278 | + | ||
| 279 | + | impl<'a, M> Tree<'a, M> |
|
| 280 | + | where |
|
| 281 | + | M: TreeModel, |
|
| 282 | + | { |
|
| 283 | + | /// Creates a tree from a model and state. |
|
| 284 | + | pub const fn new(model: &'a M, state: &'a TreeState<M::Id>) -> Self { |
|
| 285 | + | Self { |
|
| 286 | + | model, |
|
| 287 | + | state, |
|
| 288 | + | active: true, |
|
| 289 | + | style: TreeStyle::DEFAULT, |
|
| 290 | + | } |
|
| 291 | + | } |
|
| 292 | + | ||
| 293 | + | /// Sets whether the tree has active focus. |
|
| 294 | + | pub const fn active(mut self, active: bool) -> Self { |
|
| 295 | + | self.active = active; |
|
| 296 | + | self |
|
| 297 | + | } |
|
| 298 | + | ||
| 299 | + | /// Sets the tree style. |
|
| 300 | + | pub const fn style(mut self, style: TreeStyle) -> Self { |
|
| 301 | + | self.style = style; |
|
| 302 | + | self |
|
| 303 | + | } |
|
| 304 | + | ||
| 305 | + | /// Walks tree rows in render order. |
|
| 306 | + | fn walk(&self, mut visit: impl FnMut(TreeVisibleRow<M::Id>) -> bool) { |
|
| 307 | + | let roots = self.model.roots(); |
|
| 308 | + | let mut stack = Vec::with_capacity(roots.len()); |
|
| 309 | + | stack.extend(roots.iter().rev().map(|&id| (id, 0))); |
|
| 310 | + | ||
| 311 | + | while let Some((id, depth)) = stack.pop() { |
|
| 312 | + | let kind = self.model.kind(id); |
|
| 313 | + | let state = match kind { |
|
| 314 | + | TreeNodeKind::Leaf => TreeNodeState::Leaf, |
|
| 315 | + | TreeNodeKind::Branch if self.state.is_expanded(id) => TreeNodeState::Expanded, |
|
| 316 | + | TreeNodeKind::Branch => TreeNodeState::Collapsed, |
|
| 317 | + | }; |
|
| 318 | + | let enter = visit(TreeVisibleRow { id, depth, state }); |
|
| 319 | + | if enter && kind == TreeNodeKind::Branch { |
|
| 320 | + | stack.extend( |
|
| 321 | + | self.model |
|
| 322 | + | .children(id) |
|
| 323 | + | .iter() |
|
| 324 | + | .rev() |
|
| 325 | + | .map(|&child| (child, depth + 1)), |
|
| 326 | + | ); |
|
| 327 | + | } |
|
| 328 | + | } |
|
| 329 | + | } |
|
| 330 | + | ||
| 331 | + | /// Returns all rows visible under the current expansion state. |
|
| 332 | + | pub fn visible_rows(&self) -> Vec<TreeVisibleRow<M::Id>> { |
|
| 333 | + | let mut rows = Vec::new(); |
|
| 334 | + | self.walk(|row| { |
|
| 335 | + | rows.push(row); |
|
| 336 | + | row.state == TreeNodeState::Expanded |
|
| 337 | + | }); |
|
| 338 | + | rows |
|
| 339 | + | } |
|
| 340 | + | ||
| 341 | + | /// Returns the number of visible rows. |
|
| 342 | + | pub fn content_rows(&self) -> usize { |
|
| 343 | + | let mut count = 0; |
|
| 344 | + | self.walk(|row| { |
|
| 345 | + | count += 1; |
|
| 346 | + | row.state == TreeNodeState::Expanded |
|
| 347 | + | }); |
|
| 348 | + | count |
|
| 349 | + | } |
|
| 350 | + | ||
| 351 | + | /// Renders one visible row for `cols` columns. |
|
| 352 | + | pub fn render_row(&self, visible: TreeVisibleRow<M::Id>, cols: usize) -> Line { |
|
| 353 | + | if cols == 0 { |
|
| 354 | + | return Line::blank(); |
|
| 355 | + | } |
|
| 356 | + | let row = self.model.row(visible.id); |
|
| 357 | + | let indent_cols = visible.depth.saturating_mul(INDENT_COLS); |
|
| 358 | + | let prefix_cols = indent_cols.saturating_add(MARKER_COLS); |
|
| 359 | + | let mut line = Line::blank(); |
|
| 360 | + | ||
| 361 | + | if indent_cols > 0 { |
|
| 362 | + | line.push(Label::from(" ".repeat(indent_cols))); |
|
| 363 | + | } |
|
| 364 | + | line.push(Label::from_char(visible.state.marker())); |
|
| 365 | + | line.push(Label::space()); |
|
| 366 | + | ||
| 367 | + | if prefix_cols < cols { |
|
| 368 | + | let detail_width = row.detail.width(); |
|
| 369 | + | let detail_fits = detail_width > 0 |
|
| 370 | + | && detail_width |
|
| 371 | + | .saturating_add(DETAIL_GAP_COLS) |
|
| 372 | + | .saturating_add(prefix_cols) |
|
| 373 | + | < cols; |
|
| 374 | + | if detail_fits { |
|
| 375 | + | let left_cols = cols - detail_width; |
|
| 376 | + | let label_cols = left_cols.saturating_sub(prefix_cols); |
|
| 377 | + | ||
| 378 | + | line = line.extend(row.label.truncated(label_cols, "…")); |
|
| 379 | + | line.pad(left_cols); |
|
| 380 | + | line = line.extend(row.detail); |
|
| 381 | + | } else { |
|
| 382 | + | line = line.extend(row.label.truncated(cols - prefix_cols, "…")); |
|
| 383 | + | } |
|
| 384 | + | } |
|
| 385 | + | ||
| 386 | + | let line = line.truncated(cols, "…"); |
|
| 387 | + | if self.state.selected == Some(visible.id) { |
|
| 388 | + | let style = if self.active { |
|
| 389 | + | self.style.selected_active |
|
| 390 | + | } else { |
|
| 391 | + | self.style.selected_inactive |
|
| 392 | + | }; |
|
| 393 | + | return line.style(style).padded(cols); |
|
| 394 | + | } |
|
| 395 | + | line |
|
| 396 | + | } |
|
| 397 | + | } |
|
| 398 | + | ||
| 399 | + | impl<M> Widget for Tree<'_, M> |
|
| 400 | + | where |
|
| 401 | + | M: TreeModel + Sync, |
|
| 402 | + | M::Id: Sync, |
|
| 403 | + | { |
|
| 404 | + | fn size(&self, parent: Constraint) -> Size { |
|
| 405 | + | Size::new(parent.max.cols, self.content_rows()).constrain(parent) |
|
| 406 | + | } |
|
| 407 | + | ||
| 408 | + | fn render(&mut self, area: Rect, buf: &mut Buffer) { |
|
| 409 | + | if area.is_empty() { |
|
| 410 | + | return; |
|
| 411 | + | } |
|
| 412 | + | let lines = self |
|
| 413 | + | .visible_rows() |
|
| 414 | + | .into_iter() |
|
| 415 | + | .map(|row| self.render_row(row, area.cols)); |
|
| 416 | + | ||
| 417 | + | Line::renders(lines, area, buf); |
|
| 418 | + | } |
|
| 419 | + | } |
|
| 420 | + | ||
| 421 | + | #[cfg(test)] |
|
| 422 | + | mod tests { |
|
| 423 | + | use super::*; |
|
| 424 | + | use crate::ScrollView; |
|
| 425 | + | ||
| 426 | + | /// Test id for the source root. |
|
| 427 | + | const SRC: usize = 0; |
|
| 428 | + | /// Test id for the library file. |
|
| 429 | + | const LIB: usize = 1; |
|
| 430 | + | /// Test id for the tree file. |
|
| 431 | + | const TREE_FILE: usize = 2; |
|
| 432 | + | /// Test id for the widgets branch. |
|
| 433 | + | const WIDGETS: usize = 4; |
|
| 434 | + | /// Test id for the README file. |
|
| 435 | + | const README: usize = 5; |
|
| 436 | + | ||
| 437 | + | /// Test tree node. |
|
| 438 | + | #[derive(Debug, Clone)] |
|
| 439 | + | struct Node { |
|
| 440 | + | /// Rendered node name. |
|
| 441 | + | name: &'static str, |
|
| 442 | + | /// Optional right-side marker. |
|
| 443 | + | detail: &'static str, |
|
| 444 | + | /// Child node ids. |
|
| 445 | + | children: Vec<usize>, |
|
| 446 | + | } |
|
| 447 | + | ||
| 448 | + | /// Test tree model. |
|
| 449 | + | #[derive(Debug, Clone)] |
|
| 450 | + | struct Model { |
|
| 451 | + | /// Root node ids. |
|
| 452 | + | roots: Vec<usize>, |
|
| 453 | + | /// Tree nodes indexed by id. |
|
| 454 | + | nodes: Vec<Node>, |
|
| 455 | + | } |
|
| 456 | + | ||
| 457 | + | impl Model { |
|
| 458 | + | /// Creates a model with nested source and README rows. |
|
| 459 | + | fn sample() -> Self { |
|
| 460 | + | Self { |
|
| 461 | + | roots: vec![SRC, README], |
|
| 462 | + | nodes: vec![ |
|
| 463 | + | Node { |
|
| 464 | + | name: "src", |
|
| 465 | + | detail: "***", |
|
| 466 | + | children: vec![LIB, WIDGETS], |
|
| 467 | + | }, |
|
| 468 | + | Node { |
|
| 469 | + | name: "lib.rs", |
|
| 470 | + | detail: "*", |
|
| 471 | + | children: Vec::new(), |
|
| 472 | + | }, |
|
| 473 | + | Node { |
|
| 474 | + | name: "tree.rs", |
|
| 475 | + | detail: "***", |
|
| 476 | + | children: Vec::new(), |
|
| 477 | + | }, |
|
| 478 | + | Node { |
|
| 479 | + | name: "unused", |
|
| 480 | + | detail: "", |
|
| 481 | + | children: Vec::new(), |
|
| 482 | + | }, |
|
| 483 | + | Node { |
|
| 484 | + | name: "widgets", |
|
| 485 | + | detail: "", |
|
| 486 | + | children: vec![TREE_FILE], |
|
| 487 | + | }, |
|
| 488 | + | Node { |
|
| 489 | + | name: "README.md", |
|
| 490 | + | detail: "", |
|
| 491 | + | children: Vec::new(), |
|
| 492 | + | }, |
|
| 493 | + | ], |
|
| 494 | + | } |
|
| 495 | + | } |
|
| 496 | + | } |
|
| 497 | + | ||
| 498 | + | impl TreeModel for Model { |
|
| 499 | + | type Id = usize; |
|
| 500 | + | ||
| 501 | + | fn roots(&self) -> &[Self::Id] { |
|
| 502 | + | &self.roots |
|
| 503 | + | } |
|
| 504 | + | ||
| 505 | + | fn children(&self, id: Self::Id) -> &[Self::Id] { |
|
| 506 | + | &self.nodes[id].children |
|
| 507 | + | } |
|
| 508 | + | ||
| 509 | + | fn kind(&self, id: Self::Id) -> TreeNodeKind { |
|
| 510 | + | if self.nodes[id].children.is_empty() { |
|
| 511 | + | TreeNodeKind::Leaf |
|
| 512 | + | } else { |
|
| 513 | + | TreeNodeKind::Branch |
|
| 514 | + | } |
|
| 515 | + | } |
|
| 516 | + | ||
| 517 | + | fn row(&self, id: Self::Id) -> TreeRow { |
|
| 518 | + | TreeRow::new(self.nodes[id].name).detail(self.nodes[id].detail) |
|
| 519 | + | } |
|
| 520 | + | } |
|
| 521 | + | ||
| 522 | + | /// Returns visible row ids for the current state. |
|
| 523 | + | fn visible_ids(model: &Model, state: &TreeState<usize>) -> Vec<usize> { |
|
| 524 | + | Tree::new(model, state) |
|
| 525 | + | .visible_rows() |
|
| 526 | + | .into_iter() |
|
| 527 | + | .map(|row| row.id) |
|
| 528 | + | .collect() |
|
| 529 | + | } |
|
| 530 | + | ||
| 531 | + | /// Returns visible row identity and state for the current state. |
|
| 532 | + | fn visible_states( |
|
| 533 | + | model: &Model, |
|
| 534 | + | state: &TreeState<usize>, |
|
| 535 | + | ) -> Vec<(usize, usize, TreeNodeState)> { |
|
| 536 | + | Tree::new(model, state) |
|
| 537 | + | .visible_rows() |
|
| 538 | + | .into_iter() |
|
| 539 | + | .map(|row| (row.id, row.depth, row.state)) |
|
| 540 | + | .collect() |
|
| 541 | + | } |
|
| 542 | + | ||
| 543 | + | /// Checks rendered lines against a golden fixture. |
|
| 544 | + | fn assert_golden(name: &str, expected: &str, lines: Vec<String>) { |
|
| 545 | + | assert_eq!(lines.join("\n"), expected.trim_end_matches('\n'), "{name}"); |
|
| 546 | + | } |
|
| 547 | + | ||
| 548 | + | #[test] |
|
| 549 | + | fn expansion_controls_visible_descendants() { |
|
| 550 | + | let model = Model::sample(); |
|
| 551 | + | let mut state = TreeState::new(); |
|
| 552 | + | ||
| 553 | + | assert_eq!(visible_ids(&model, &state), vec![SRC, README]); |
|
| 554 | + | state.expand(SRC); |
|
| 555 | + | ||
| 556 | + | assert_eq!( |
|
| 557 | + | visible_states(&model, &state), |
|
| 558 | + | vec![ |
|
| 559 | + | (SRC, 0, TreeNodeState::Expanded), |
|
| 560 | + | (LIB, 1, TreeNodeState::Leaf), |
|
| 561 | + | (WIDGETS, 1, TreeNodeState::Collapsed), |
|
| 562 | + | (README, 0, TreeNodeState::Leaf), |
|
| 563 | + | ] |
|
| 564 | + | ); |
|
| 565 | + | state.expand(WIDGETS); |
|
| 566 | + | ||
| 567 | + | assert_eq!( |
|
| 568 | + | visible_ids(&model, &state), |
|
| 569 | + | vec![SRC, LIB, WIDGETS, TREE_FILE, README] |
|
| 570 | + | ); |
|
| 571 | + | } |
|
| 572 | + | ||
| 573 | + | #[test] |
|
| 574 | + | fn walk_callback_controls_branch_descent() { |
|
| 575 | + | let model = Model::sample(); |
|
| 576 | + | let mut state = TreeState::new(); |
|
| 577 | + | let mut visited = Vec::new(); |
|
| 578 | + | ||
| 579 | + | Tree::new(&model, &state).walk(|row| { |
|
| 580 | + | visited.push(row.id); |
|
| 581 | + | true |
|
| 582 | + | }); |
|
| 583 | + | assert_eq!(visited, vec![SRC, LIB, WIDGETS, TREE_FILE, README]); |
|
| 584 | + | ||
| 585 | + | visited.clear(); |
|
| 586 | + | state.expand(SRC); |
|
| 587 | + | state.expand(WIDGETS); |
|
| 588 | + | Tree::new(&model, &state).walk(|row| { |
|
| 589 | + | visited.push(row.id); |
|
| 590 | + | row.id != SRC |
|
| 591 | + | }); |
|
| 592 | + | ||
| 593 | + | assert_eq!(visited, vec![SRC, README]); |
|
| 594 | + | } |
|
| 595 | + | ||
| 596 | + | #[test] |
|
| 597 | + | fn selection_moves_over_visible_rows() { |
|
| 598 | + | let model = Model::sample(); |
|
| 599 | + | let mut state = TreeState::new(); |
|
| 600 | + | ||
| 601 | + | state.expand(SRC); |
|
| 602 | + | assert!(state.select_nth(&model, 0)); |
|
| 603 | + | assert_eq!(state.selected(), Some(SRC)); |
|
| 604 | + | assert!(state.select_nth(&model, 2)); |
|
| 605 | + | assert_eq!(state.selected(), Some(WIDGETS)); |
|
| 606 | + | assert!(state.select_next(&model, 2)); |
|
| 607 | + | assert_eq!(state.selected(), Some(README)); |
|
| 608 | + | assert!(state.select_next(&model, -99)); |
|
| 609 | + | assert_eq!(state.selected(), Some(SRC)); |
|
| 610 | + | } |
|
| 611 | + | ||
| 612 | + | #[test] |
|
| 613 | + | fn toggling_selected_branch_changes_visible_rows() { |
|
| 614 | + | let model = Model::sample(); |
|
| 615 | + | let mut state = TreeState::new(); |
|
| 616 | + | ||
| 617 | + | state.select(SRC); |
|
| 618 | + | assert_eq!(state.toggle_selected(&model), Some(TreeNodeState::Expanded)); |
|
| 619 | + | assert_eq!(Tree::new(&model, &state).content_rows(), 4); |
|
| 620 | + | assert_eq!( |
|
| 621 | + | state.toggle_selected(&model), |
|
| 622 | + | Some(TreeNodeState::Collapsed) |
|
| 623 | + | ); |
|
| 624 | + | assert_eq!(Tree::new(&model, &state).content_rows(), 2); |
|
| 625 | + | ||
| 626 | + | state.select(README); |
|
| 627 | + | assert_eq!(state.toggle_selected(&model), None); |
|
| 628 | + | } |
|
| 629 | + | ||
| 630 | + | #[test] |
|
| 631 | + | fn render_row_indents_markers_and_right_aligns_detail() { |
|
| 632 | + | let model = Model::sample(); |
|
| 633 | + | let mut state = TreeState::new(); |
|
| 634 | + | ||
| 635 | + | state.expand(SRC); |
|
| 636 | + | let tree = Tree::new(&model, &state); |
|
| 637 | + | let rows = tree.visible_rows(); |
|
| 638 | + | ||
| 639 | + | assert_golden( |
|
| 640 | + | "tree row rendering", |
|
| 641 | + | include_str!("../tests/golden/tree_rows_16x3.txt"), |
|
| 642 | + | rows.into_iter() |
|
| 643 | + | .take(3) |
|
| 644 | + | .map(|row| tree.render_row(row, 16).to_string()) |
|
| 645 | + | .collect(), |
|
| 646 | + | ); |
|
| 647 | + | } |
|
| 648 | + | ||
| 649 | + | #[test] |
|
| 650 | + | fn selected_row_uses_full_width_style() { |
|
| 651 | + | let model = Model::sample(); |
|
| 652 | + | let mut state = TreeState::new(); |
|
| 653 | + | ||
| 654 | + | state.select(README); |
|
| 655 | + | let mut tree = Tree::new(&model, &state); |
|
| 656 | + | let mut buffer = Buffer::empty(Rect::new(0, 0, 14, 2)); |
|
| 657 | + | ||
| 658 | + | tree.render(buffer.area(), &mut buffer); |
|
| 659 | + | ||
| 660 | + | assert_golden( |
|
| 661 | + | "selected tree frame", |
|
| 662 | + | include_str!("../tests/golden/tree_selected_14x2.txt"), |
|
| 663 | + | buffer.lines(), |
|
| 664 | + | ); |
|
| 665 | + | assert_eq!( |
|
| 666 | + | buffer.get(13, 1).map(|cell| cell.style().bg_color()), |
|
| 667 | + | Some(Color::Blue) |
|
| 668 | + | ); |
|
| 669 | + | } |
|
| 670 | + | ||
| 671 | + | #[test] |
|
| 672 | + | fn tree_rows_scroll_through_scroll_view() { |
|
| 673 | + | let model = Model::sample(); |
|
| 674 | + | let mut state = TreeState::new(); |
|
| 675 | + | ||
| 676 | + | state.expand(SRC); |
|
| 677 | + | state.expand(WIDGETS); |
|
| 678 | + | let tree = Tree::new(&model, &state); |
|
| 679 | + | let rows = tree.visible_rows(); |
|
| 680 | + | let mut view = |
|
| 681 | + | ScrollView::virtualized(rows.len(), 2, |row, cols| tree.render_row(rows[row], cols)); |
|
| 682 | + | let mut buffer = Buffer::empty(Rect::new(0, 0, 22, 2)); |
|
| 683 | + | ||
| 684 | + | view.render(buffer.area(), &mut buffer); |
|
| 685 | + | ||
| 686 | + | assert_golden( |
|
| 687 | + | "scrolled tree rows", |
|
| 688 | + | include_str!("../tests/golden/tree_scroll_22x2.txt"), |
|
| 689 | + | buffer.lines(), |
|
| 690 | + | ); |
|
| 691 | + | } |
|
| 692 | + | } |
crates/tui-widgets/tests/golden/tree_rows_16x3.txt
added
+3 -0
| 1 | + | ▾ src *** |
|
| 2 | + | lib.rs * |
|
| 3 | + | ▸ widgets |
crates/tui-widgets/tests/golden/tree_scroll_22x2.txt
added
+2 -0
| 1 | + | ▾ widgets ┃ |
|
| 2 | + | tree.rs ***│ |
crates/tui-widgets/tests/golden/tree_selected_14x2.txt
added
+2 -0
| 1 | + | ▸ src *** |
|
| 2 | + | README.md |