.cargo/
crates/
brain/
diff/
files/
highlight/
repo/
signals/
tui/
tui-core/
tui-termion/
tui-widgets/
benches/
src/
action_bar.rs
4.7 KiB
badge.rs
2.6 KiB
dialog.rs
12.4 KiB
input.rs
13.3 KiB
lib.rs
1.6 KiB
list.rs
13.1 KiB
overlay.rs
3.4 KiB
panel.rs
18.6 KiB
scrollbar.rs
5.9 KiB
scrollview.rs
13.2 KiB
tree.rs
27.9 KiB
viewport.rs
15.7 KiB
tests/
Cargo.toml
408 B
README.md
294 B
scripts/
src/
.gitignore
30 B
.gitsigners
198 B
AGENTS.md
1.9 KiB
CONTRIBUTING
1.7 KiB
Cargo.lock
5.4 KiB
Cargo.toml
1.9 KiB
LICENSE
1.1 KiB
README.md
245 B
STYLE
3.7 KiB
clippy.toml
213 B
crates/tui-widgets/src/tree.rs
raw
| 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 crate::{Placement, View}; |
| 12 | use rustik_tui_core::{Buffer, Color, Constraint, Label, Line, Point, Rect, Size, Style, Widget}; |
| 13 | |
| 14 | /// Columns added for each tree depth. |
| 15 | const INDENT_COLS: usize = 2; |
| 16 | /// Columns reserved for the branch marker and following space. |
| 17 | const MARKER_COLS: usize = 2; |
| 18 | /// Minimum gap between the row label and right-side detail text. |
| 19 | const DETAIL_GAP_COLS: usize = 2; |
| 20 | |
| 21 | /// Caller-owned data adapter for a renderable tree. |
| 22 | pub trait TreeModel { |
| 23 | /// Stable node identifier. |
| 24 | type Id: Copy + Ord; |
| 25 | |
| 26 | /// Returns the root node ids in render order. |
| 27 | fn roots(&self) -> &[Self::Id]; |
| 28 | /// Returns child node ids for `id` in render order. |
| 29 | fn children(&self, id: Self::Id) -> &[Self::Id]; |
| 30 | /// Returns whether `id` is a branch or leaf. |
| 31 | fn kind(&self, id: Self::Id) -> TreeNodeKind; |
| 32 | /// Returns the row content for `id`. |
| 33 | fn row(&self, id: Self::Id) -> TreeRow; |
| 34 | } |
| 35 | |
| 36 | /// Structural role of a tree node. |
| 37 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 38 | pub enum TreeNodeKind { |
| 39 | /// Node with collapsible children. |
| 40 | Branch, |
| 41 | /// Node without collapsible children. |
| 42 | Leaf, |
| 43 | } |
| 44 | |
| 45 | /// Render content for one tree row. |
| 46 | #[derive(Debug, Clone, Default)] |
| 47 | pub struct TreeRow { |
| 48 | /// Main row label. |
| 49 | pub label: Line, |
| 50 | /// Optional right-aligned row detail. |
| 51 | pub detail: Line, |
| 52 | /// Marker glyph rendered in the fixed tree marker column. |
| 53 | pub marker: Option<char>, |
| 54 | /// Style applied to the branch or leaf marker. |
| 55 | pub marker_style: Style, |
| 56 | /// Full-width row style applied when the row is not selected. |
| 57 | pub style: Style, |
| 58 | } |
| 59 | |
| 60 | impl TreeRow { |
| 61 | /// Creates a row with a label and no detail. |
| 62 | pub fn new(label: impl Into<Line>) -> Self { |
| 63 | Self { |
| 64 | label: label.into(), |
| 65 | detail: Line::blank(), |
| 66 | marker: None, |
| 67 | marker_style: Style::default(), |
| 68 | style: Style::default(), |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// Sets the right-aligned detail text. |
| 73 | pub fn detail(mut self, detail: impl Into<Line>) -> Self { |
| 74 | self.detail = detail.into(); |
| 75 | self |
| 76 | } |
| 77 | |
| 78 | /// Sets the marker glyph. |
| 79 | pub fn marker(mut self, marker: char) -> Self { |
| 80 | self.marker = Some(marker); |
| 81 | self |
| 82 | } |
| 83 | |
| 84 | /// Sets the branch or leaf marker style. |
| 85 | pub fn marker_style(mut self, style: Style) -> Self { |
| 86 | self.marker_style = style; |
| 87 | self |
| 88 | } |
| 89 | |
| 90 | /// Sets the full-width row style. |
| 91 | pub fn style(mut self, style: Style) -> Self { |
| 92 | self.style = style; |
| 93 | self |
| 94 | } |
| 95 | |
| 96 | /// Returns the columns needed to render this row without truncation. |
| 97 | pub fn width(&self) -> usize { |
| 98 | let w = self.detail.width(); |
| 99 | let w = if w == 0 { |
| 100 | 0 |
| 101 | } else { |
| 102 | w.saturating_add(DETAIL_GAP_COLS) |
| 103 | }; |
| 104 | self.label.width().saturating_add(w) |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | /// Visual styling for a tree widget. |
| 109 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 110 | pub struct TreeStyle { |
| 111 | /// Style applied to the selected row while the tree is active. |
| 112 | pub selected_active: Style, |
| 113 | /// Style applied to the selected row while the tree is inactive. |
| 114 | pub selected_inactive: Style, |
| 115 | /// Glyph used for expanded branches. |
| 116 | pub expanded_marker: char, |
| 117 | /// Glyph used for collapsed branches. |
| 118 | pub collapsed_marker: char, |
| 119 | /// Glyph used for leaves. |
| 120 | pub leaf_marker: char, |
| 121 | } |
| 122 | |
| 123 | impl TreeStyle { |
| 124 | /// Default tree style. |
| 125 | pub const DEFAULT: Self = Self { |
| 126 | selected_active: Style::new(Color::Unset).bg(Color::Blue), |
| 127 | selected_inactive: Style::new(Color::Unset).bg(Color::Fixed(238)), |
| 128 | expanded_marker: '▿', |
| 129 | collapsed_marker: '▹', |
| 130 | leaf_marker: ' ', |
| 131 | }; |
| 132 | |
| 133 | /// Creates a tree style from selected-row styles, keeping the default markers. |
| 134 | pub const fn new(selected_active: Style, selected_inactive: Style) -> Self { |
| 135 | Self { |
| 136 | selected_active, |
| 137 | selected_inactive, |
| 138 | expanded_marker: Self::DEFAULT.expanded_marker, |
| 139 | collapsed_marker: Self::DEFAULT.collapsed_marker, |
| 140 | leaf_marker: Self::DEFAULT.leaf_marker, |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /// Returns the marker glyph for a visible node state. |
| 145 | pub const fn marker_for(&self, state: TreeNodeState) -> char { |
| 146 | match state { |
| 147 | TreeNodeState::Leaf => self.leaf_marker, |
| 148 | TreeNodeState::Collapsed => self.collapsed_marker, |
| 149 | TreeNodeState::Expanded => self.expanded_marker, |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | impl Default for TreeStyle { |
| 155 | fn default() -> Self { |
| 156 | Self::DEFAULT |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// Expansion and selection state for a tree. |
| 161 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 162 | pub struct TreeState<Id> { |
| 163 | /// Expanded branch ids. |
| 164 | pub expanded: BTreeSet<Id>, |
| 165 | /// Selected node (cursor). |
| 166 | pub selected: Option<Id>, |
| 167 | /// Pivot used by range selection. |
| 168 | pub anchor: Option<Id>, |
| 169 | } |
| 170 | |
| 171 | impl<Id> TreeState<Id> |
| 172 | where |
| 173 | Id: Copy + Ord, |
| 174 | { |
| 175 | /// Creates empty tree state. |
| 176 | pub fn new() -> Self { |
| 177 | Self { |
| 178 | expanded: BTreeSet::new(), |
| 179 | selected: None, |
| 180 | anchor: None, |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /// Returns whether `id` is expanded. |
| 185 | pub fn is_expanded(&self, id: Id) -> bool { |
| 186 | self.expanded.contains(&id) |
| 187 | } |
| 188 | |
| 189 | /// Expands `id` and returns whether the state changed. |
| 190 | pub fn expand(&mut self, id: Id) -> bool { |
| 191 | self.expanded.insert(id) |
| 192 | } |
| 193 | |
| 194 | /// Collapses `id` and returns whether the state changed. |
| 195 | pub fn collapse(&mut self, id: Id) -> bool { |
| 196 | self.expanded.remove(&id) |
| 197 | } |
| 198 | |
| 199 | /// Toggles `id` if it is a branch and returns whether it is expanded afterward. |
| 200 | pub fn toggle<M>(&mut self, model: &M, id: Id) -> Option<TreeNodeState> |
| 201 | where |
| 202 | M: TreeModel<Id = Id>, |
| 203 | { |
| 204 | if model.kind(id) == TreeNodeKind::Leaf { |
| 205 | return None; |
| 206 | } |
| 207 | if self.expanded.remove(&id) { |
| 208 | Some(TreeNodeState::Collapsed) |
| 209 | } else { |
| 210 | self.expanded.insert(id); |
| 211 | Some(TreeNodeState::Expanded) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | /// Sets the selected node and resets the anchor to it. |
| 216 | pub fn select(&mut self, id: Id) -> bool { |
| 217 | let changed = self.selected != Some(id); |
| 218 | self.selected = Some(id); |
| 219 | self.anchor = Some(id); |
| 220 | changed |
| 221 | } |
| 222 | |
| 223 | /// Clears the selected node and the anchor. |
| 224 | pub fn clear_selection(&mut self) -> bool { |
| 225 | self.anchor = None; |
| 226 | self.selected.take().is_some() |
| 227 | } |
| 228 | |
| 229 | /// Returns the selected node. |
| 230 | pub const fn selected(&self) -> Option<Id> { |
| 231 | self.selected |
| 232 | } |
| 233 | |
| 234 | /// Returns the anchor node. |
| 235 | pub const fn anchor(&self) -> Option<Id> { |
| 236 | self.anchor |
| 237 | } |
| 238 | |
| 239 | /// Sets the anchor without changing the selection. |
| 240 | pub fn set_anchor(&mut self, id: Option<Id>) { |
| 241 | self.anchor = id; |
| 242 | } |
| 243 | |
| 244 | /// Selects the zero-based visible node. |
| 245 | pub fn select_nth<M>(&mut self, model: &M, index: usize) -> bool |
| 246 | where |
| 247 | M: TreeModel<Id = Id>, |
| 248 | { |
| 249 | let row = Tree::new(model, self).visible_rows().get(index).copied(); |
| 250 | let Some(row) = row else { |
| 251 | return self.clear_selection(); |
| 252 | }; |
| 253 | self.select(row.id) |
| 254 | } |
| 255 | |
| 256 | /// Moves selection by `delta` visible rows. |
| 257 | pub fn select_next<M>(&mut self, model: &M, delta: isize) -> bool |
| 258 | where |
| 259 | M: TreeModel<Id = Id>, |
| 260 | { |
| 261 | let rows = Tree::new(model, self).visible_rows(); |
| 262 | if rows.is_empty() { |
| 263 | return self.clear_selection(); |
| 264 | } |
| 265 | let index = self |
| 266 | .selected |
| 267 | .and_then(|id| rows.iter().position(|row| row.id == id)) |
| 268 | .unwrap_or(0); |
| 269 | let next = if delta.is_negative() { |
| 270 | index.saturating_sub(delta.unsigned_abs()) |
| 271 | } else { |
| 272 | index.saturating_add(delta as usize).min(rows.len() - 1) |
| 273 | }; |
| 274 | self.select(rows[next].id) |
| 275 | } |
| 276 | |
| 277 | /// Moves selection by `delta` and returns the ids between the anchor and the |
| 278 | /// new selection in visible-row order, inclusive on both ends. |
| 279 | /// |
| 280 | /// The anchor is preserved across calls so successive extends grow or shrink |
| 281 | /// the same range. If the anchor is unset or no longer visible, it is reset |
| 282 | /// to the new cursor and a single-element range is returned. |
| 283 | pub fn extend_selection<M>(&mut self, model: &M, delta: isize) -> Vec<Id> |
| 284 | where |
| 285 | M: TreeModel<Id = Id>, |
| 286 | { |
| 287 | let rows = Tree::new(model, self).visible_rows(); |
| 288 | if rows.is_empty() { |
| 289 | self.clear_selection(); |
| 290 | return Vec::new(); |
| 291 | } |
| 292 | let index = self |
| 293 | .selected |
| 294 | .and_then(|id| rows.iter().position(|row| row.id == id)) |
| 295 | .unwrap_or(0); |
| 296 | |
| 297 | let next = if delta.is_negative() { |
| 298 | index.saturating_sub(delta.unsigned_abs()) |
| 299 | } else { |
| 300 | index.saturating_add(delta as usize).min(rows.len() - 1) |
| 301 | }; |
| 302 | self.selected = Some(rows[next].id); |
| 303 | |
| 304 | let anchor_idx = self |
| 305 | .anchor |
| 306 | .and_then(|id| rows.iter().position(|row| row.id == id)) |
| 307 | .unwrap_or(next); |
| 308 | self.anchor = Some(rows[anchor_idx].id); |
| 309 | |
| 310 | let (lo, hi) = if anchor_idx <= next { |
| 311 | (anchor_idx, next) |
| 312 | } else { |
| 313 | (next, anchor_idx) |
| 314 | }; |
| 315 | rows[lo..=hi].iter().map(|row| row.id).collect() |
| 316 | } |
| 317 | |
| 318 | /// Toggles the selected branch if a branch is selected. |
| 319 | pub fn toggle_selected<M>(&mut self, model: &M) -> Option<TreeNodeState> |
| 320 | where |
| 321 | M: TreeModel<Id = Id>, |
| 322 | { |
| 323 | self.selected |
| 324 | .and_then(|selected| self.toggle(model, selected)) |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | /// Render state of a visible tree node. |
| 329 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 330 | pub enum TreeNodeState { |
| 331 | /// Node has no collapsible children. |
| 332 | Leaf, |
| 333 | /// Branch is collapsed. |
| 334 | Collapsed, |
| 335 | /// Branch is expanded. |
| 336 | Expanded, |
| 337 | } |
| 338 | |
| 339 | /// One rendered row in tree order before terminal-width layout. |
| 340 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 341 | pub struct TreeVisibleRow<Id> { |
| 342 | /// Node id for this row. |
| 343 | pub id: Id, |
| 344 | /// Zero-based tree depth. |
| 345 | pub depth: usize, |
| 346 | /// Visible expansion state. |
| 347 | pub state: TreeNodeState, |
| 348 | } |
| 349 | |
| 350 | /// Region hit inside a rendered tree row. |
| 351 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 352 | pub enum TreeHitZone { |
| 353 | /// Branch or leaf marker column. |
| 354 | Marker, |
| 355 | /// Row content outside the marker column. |
| 356 | Content, |
| 357 | } |
| 358 | |
| 359 | /// Tree row hit by a screen point. |
| 360 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 361 | pub struct TreeHit<Id> { |
| 362 | /// Visible row hit by the point. |
| 363 | pub row: TreeVisibleRow<Id>, |
| 364 | /// Region hit inside the visible row. |
| 365 | pub zone: TreeHitZone, |
| 366 | } |
| 367 | |
| 368 | /// Generic tree widget over caller-owned data. |
| 369 | #[derive(Clone)] |
| 370 | pub struct Tree<'a, M> |
| 371 | where |
| 372 | M: TreeModel, |
| 373 | { |
| 374 | /// Tree data model. |
| 375 | model: &'a M, |
| 376 | /// Expansion and selection state. |
| 377 | state: &'a TreeState<M::Id>, |
| 378 | /// Whether the tree has active focus. |
| 379 | active: bool, |
| 380 | /// Tree styling. |
| 381 | style: TreeStyle, |
| 382 | } |
| 383 | |
| 384 | impl<M> fmt::Debug for Tree<'_, M> |
| 385 | where |
| 386 | M: TreeModel, |
| 387 | { |
| 388 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 389 | f.debug_struct("Tree") |
| 390 | .field("active", &self.active) |
| 391 | .field("style", &self.style) |
| 392 | .finish_non_exhaustive() |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | impl<'a, M> Tree<'a, M> |
| 397 | where |
| 398 | M: TreeModel, |
| 399 | { |
| 400 | /// Creates a tree from a model and state. |
| 401 | pub const fn new(model: &'a M, state: &'a TreeState<M::Id>) -> Self { |
| 402 | Self { |
| 403 | model, |
| 404 | state, |
| 405 | active: true, |
| 406 | style: TreeStyle::DEFAULT, |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | /// Sets whether the tree has active focus. |
| 411 | pub const fn active(mut self, active: bool) -> Self { |
| 412 | self.active = active; |
| 413 | self |
| 414 | } |
| 415 | |
| 416 | /// Sets the tree style. |
| 417 | pub const fn style(mut self, style: TreeStyle) -> Self { |
| 418 | self.style = style; |
| 419 | self |
| 420 | } |
| 421 | |
| 422 | /// Returns columns needed to render any tree row without truncation. |
| 423 | pub fn content_cols(&self, minimum: usize) -> usize { |
| 424 | let mut cols = minimum; |
| 425 | |
| 426 | self.walk(|row| { |
| 427 | let prefix_cols = row |
| 428 | .depth |
| 429 | .saturating_mul(INDENT_COLS) |
| 430 | .saturating_add(MARKER_COLS); |
| 431 | cols = cols.max(prefix_cols.saturating_add(self.model.row(row.id).width())); |
| 432 | true |
| 433 | }); |
| 434 | cols |
| 435 | } |
| 436 | |
| 437 | /// Returns the visible index of the selected row. |
| 438 | pub fn selected_row(&self, rows: &[TreeVisibleRow<M::Id>]) -> Option<usize> { |
| 439 | let selected = self.state.selected?; |
| 440 | |
| 441 | rows.iter().position(|row| row.id == selected) |
| 442 | } |
| 443 | |
| 444 | /// Returns a view that keeps the selected row visible. |
| 445 | pub fn selected_view( |
| 446 | &self, |
| 447 | rows: &[TreeVisibleRow<M::Id>], |
| 448 | visible_rows: usize, |
| 449 | placement: Placement, |
| 450 | ) -> View { |
| 451 | let row = self.selected_row(rows).unwrap_or_default(); |
| 452 | |
| 453 | View::new(0, rows.len(), visible_rows).with_row_visible(row, placement) |
| 454 | } |
| 455 | |
| 456 | /// Returns the visible row and row region under `point`. |
| 457 | pub fn hit_test( |
| 458 | &self, |
| 459 | rows: &[TreeVisibleRow<M::Id>], |
| 460 | view: View, |
| 461 | area: Rect, |
| 462 | point: Point, |
| 463 | ) -> Option<TreeHit<M::Id>> { |
| 464 | let index = view.row_at(area, point)?; |
| 465 | let row = rows.get(index).copied()?; |
| 466 | let x = point.x.saturating_sub(area.x); |
| 467 | let zone = if x == row.depth.saturating_mul(INDENT_COLS) { |
| 468 | TreeHitZone::Marker |
| 469 | } else { |
| 470 | TreeHitZone::Content |
| 471 | }; |
| 472 | |
| 473 | Some(TreeHit { row, zone }) |
| 474 | } |
| 475 | |
| 476 | /// Walks tree rows in render order. |
| 477 | fn walk(&self, mut visit: impl FnMut(TreeVisibleRow<M::Id>) -> bool) { |
| 478 | let roots = self.model.roots(); |
| 479 | let mut stack = Vec::with_capacity(roots.len()); |
| 480 | stack.extend(roots.iter().rev().map(|&id| (id, 0))); |
| 481 | |
| 482 | while let Some((id, depth)) = stack.pop() { |
| 483 | let kind = self.model.kind(id); |
| 484 | let state = match kind { |
| 485 | TreeNodeKind::Leaf => TreeNodeState::Leaf, |
| 486 | TreeNodeKind::Branch if self.state.is_expanded(id) => TreeNodeState::Expanded, |
| 487 | TreeNodeKind::Branch => TreeNodeState::Collapsed, |
| 488 | }; |
| 489 | let enter = visit(TreeVisibleRow { id, depth, state }); |
| 490 | if enter && kind == TreeNodeKind::Branch { |
| 491 | stack.extend( |
| 492 | self.model |
| 493 | .children(id) |
| 494 | .iter() |
| 495 | .rev() |
| 496 | .map(|&child| (child, depth + 1)), |
| 497 | ); |
| 498 | } |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | /// Returns all rows visible under the current expansion state. |
| 503 | pub fn visible_rows(&self) -> Vec<TreeVisibleRow<M::Id>> { |
| 504 | let mut rows = Vec::new(); |
| 505 | self.walk(|row| { |
| 506 | rows.push(row); |
| 507 | row.state == TreeNodeState::Expanded |
| 508 | }); |
| 509 | rows |
| 510 | } |
| 511 | |
| 512 | /// Returns the number of visible rows. |
| 513 | pub fn content_rows(&self) -> usize { |
| 514 | let mut count = 0; |
| 515 | self.walk(|row| { |
| 516 | count += 1; |
| 517 | row.state == TreeNodeState::Expanded |
| 518 | }); |
| 519 | count |
| 520 | } |
| 521 | |
| 522 | /// Renders one visible row for `cols` columns. |
| 523 | pub fn render_row(&self, visible: TreeVisibleRow<M::Id>, cols: usize) -> Line { |
| 524 | if cols == 0 { |
| 525 | return Line::blank(); |
| 526 | } |
| 527 | let row = self.model.row(visible.id); |
| 528 | let indent_cols = visible.depth.saturating_mul(INDENT_COLS); |
| 529 | let prefix_cols = indent_cols.saturating_add(MARKER_COLS); |
| 530 | let mut line = Line::blank(); |
| 531 | |
| 532 | if indent_cols > 0 { |
| 533 | line.push(Label::from(" ".repeat(indent_cols))); |
| 534 | } |
| 535 | let marker = row |
| 536 | .marker |
| 537 | .unwrap_or_else(|| self.style.marker_for(visible.state)); |
| 538 | line.push(Label::from_char(marker).style(row.marker_style)); |
| 539 | line.push(Label::space()); |
| 540 | |
| 541 | if prefix_cols < cols { |
| 542 | let detail_width = row.detail.width(); |
| 543 | let detail_fits = detail_width > 0 |
| 544 | && detail_width |
| 545 | .saturating_add(DETAIL_GAP_COLS) |
| 546 | .saturating_add(prefix_cols) |
| 547 | < cols; |
| 548 | if detail_fits { |
| 549 | let left_cols = cols - detail_width; |
| 550 | let label_cols = left_cols.saturating_sub(prefix_cols); |
| 551 | |
| 552 | line = line.extend(row.label.truncated(label_cols, "…")); |
| 553 | line.pad(left_cols); |
| 554 | line = line.extend(row.detail); |
| 555 | } else { |
| 556 | line = line.extend(row.label.truncated(cols - prefix_cols, "…")); |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | let line = line.truncated(cols, "…"); |
| 561 | let style = if self.state.selected == Some(visible.id) { |
| 562 | let selected = if self.active { |
| 563 | self.style.selected_active |
| 564 | } else { |
| 565 | self.style.selected_inactive |
| 566 | }; |
| 567 | selected.merge(row.style) |
| 568 | } else { |
| 569 | row.style |
| 570 | }; |
| 571 | |
| 572 | if style != Style::default() { |
| 573 | return line.style(style).padded(cols); |
| 574 | } |
| 575 | line |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | impl<M> Widget for Tree<'_, M> |
| 580 | where |
| 581 | M: TreeModel + Sync, |
| 582 | M::Id: Sync, |
| 583 | { |
| 584 | fn size(&self, parent: Constraint) -> Size { |
| 585 | Size::new(parent.max.cols, self.content_rows()).constrain(parent) |
| 586 | } |
| 587 | |
| 588 | fn render(&mut self, area: Rect, buf: &mut Buffer) { |
| 589 | if area.is_empty() { |
| 590 | return; |
| 591 | } |
| 592 | let lines = self |
| 593 | .visible_rows() |
| 594 | .into_iter() |
| 595 | .map(|row| self.render_row(row, area.cols)); |
| 596 | |
| 597 | Line::renders(lines, area, buf); |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | #[cfg(test)] |
| 602 | mod tests { |
| 603 | use super::*; |
| 604 | use crate::ScrollView; |
| 605 | |
| 606 | /// Test id for the source root. |
| 607 | const SRC: usize = 0; |
| 608 | /// Test id for the library file. |
| 609 | const LIB: usize = 1; |
| 610 | /// Test id for the tree file. |
| 611 | const TREE_FILE: usize = 2; |
| 612 | /// Test id for the widgets branch. |
| 613 | const WIDGETS: usize = 4; |
| 614 | /// Test id for the README file. |
| 615 | const README: usize = 5; |
| 616 | |
| 617 | /// Test tree node. |
| 618 | #[derive(Debug, Clone)] |
| 619 | struct Node { |
| 620 | /// Rendered node name. |
| 621 | name: &'static str, |
| 622 | /// Optional right-side marker. |
| 623 | detail: &'static str, |
| 624 | /// Child node ids. |
| 625 | children: Vec<usize>, |
| 626 | } |
| 627 | |
| 628 | /// Test tree model. |
| 629 | #[derive(Debug, Clone)] |
| 630 | struct Model { |
| 631 | /// Root node ids. |
| 632 | roots: Vec<usize>, |
| 633 | /// Tree nodes indexed by id. |
| 634 | nodes: Vec<Node>, |
| 635 | } |
| 636 | |
| 637 | impl Model { |
| 638 | /// Creates a model with nested source and README rows. |
| 639 | fn sample() -> Self { |
| 640 | Self { |
| 641 | roots: vec![SRC, README], |
| 642 | nodes: vec![ |
| 643 | Node { |
| 644 | name: "src", |
| 645 | detail: "***", |
| 646 | children: vec![LIB, WIDGETS], |
| 647 | }, |
| 648 | Node { |
| 649 | name: "lib.rs", |
| 650 | detail: "*", |
| 651 | children: Vec::new(), |
| 652 | }, |
| 653 | Node { |
| 654 | name: "tree.rs", |
| 655 | detail: "***", |
| 656 | children: Vec::new(), |
| 657 | }, |
| 658 | Node { |
| 659 | name: "unused", |
| 660 | detail: "", |
| 661 | children: Vec::new(), |
| 662 | }, |
| 663 | Node { |
| 664 | name: "widgets", |
| 665 | detail: "", |
| 666 | children: vec![TREE_FILE], |
| 667 | }, |
| 668 | Node { |
| 669 | name: "README.md", |
| 670 | detail: "", |
| 671 | children: Vec::new(), |
| 672 | }, |
| 673 | ], |
| 674 | } |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | impl TreeModel for Model { |
| 679 | type Id = usize; |
| 680 | |
| 681 | fn roots(&self) -> &[Self::Id] { |
| 682 | &self.roots |
| 683 | } |
| 684 | |
| 685 | fn children(&self, id: Self::Id) -> &[Self::Id] { |
| 686 | &self.nodes[id].children |
| 687 | } |
| 688 | |
| 689 | fn kind(&self, id: Self::Id) -> TreeNodeKind { |
| 690 | if self.nodes[id].children.is_empty() { |
| 691 | TreeNodeKind::Leaf |
| 692 | } else { |
| 693 | TreeNodeKind::Branch |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | fn row(&self, id: Self::Id) -> TreeRow { |
| 698 | TreeRow::new(self.nodes[id].name).detail(self.nodes[id].detail) |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | /// Returns visible row ids for the current state. |
| 703 | fn visible_ids(model: &Model, state: &TreeState<usize>) -> Vec<usize> { |
| 704 | Tree::new(model, state) |
| 705 | .visible_rows() |
| 706 | .into_iter() |
| 707 | .map(|row| row.id) |
| 708 | .collect() |
| 709 | } |
| 710 | |
| 711 | /// Returns visible row identity and state for the current state. |
| 712 | fn visible_states( |
| 713 | model: &Model, |
| 714 | state: &TreeState<usize>, |
| 715 | ) -> Vec<(usize, usize, TreeNodeState)> { |
| 716 | Tree::new(model, state) |
| 717 | .visible_rows() |
| 718 | .into_iter() |
| 719 | .map(|row| (row.id, row.depth, row.state)) |
| 720 | .collect() |
| 721 | } |
| 722 | |
| 723 | /// Checks rendered lines against a golden fixture. |
| 724 | fn assert_golden(name: &str, expected: &str, lines: Vec<String>) { |
| 725 | assert_eq!(lines.join("\n"), expected.trim_end_matches('\n'), "{name}"); |
| 726 | } |
| 727 | |
| 728 | #[test] |
| 729 | fn expansion_controls_visible_descendants() { |
| 730 | let model = Model::sample(); |
| 731 | let mut state = TreeState::new(); |
| 732 | |
| 733 | assert_eq!(visible_ids(&model, &state), vec![SRC, README]); |
| 734 | state.expand(SRC); |
| 735 | |
| 736 | assert_eq!( |
| 737 | visible_states(&model, &state), |
| 738 | vec![ |
| 739 | (SRC, 0, TreeNodeState::Expanded), |
| 740 | (LIB, 1, TreeNodeState::Leaf), |
| 741 | (WIDGETS, 1, TreeNodeState::Collapsed), |
| 742 | (README, 0, TreeNodeState::Leaf), |
| 743 | ] |
| 744 | ); |
| 745 | state.expand(WIDGETS); |
| 746 | |
| 747 | assert_eq!( |
| 748 | visible_ids(&model, &state), |
| 749 | vec![SRC, LIB, WIDGETS, TREE_FILE, README] |
| 750 | ); |
| 751 | } |
| 752 | |
| 753 | #[test] |
| 754 | fn walk_callback_controls_branch_descent() { |
| 755 | let model = Model::sample(); |
| 756 | let mut state = TreeState::new(); |
| 757 | let mut visited = Vec::new(); |
| 758 | |
| 759 | Tree::new(&model, &state).walk(|row| { |
| 760 | visited.push(row.id); |
| 761 | true |
| 762 | }); |
| 763 | assert_eq!(visited, vec![SRC, LIB, WIDGETS, TREE_FILE, README]); |
| 764 | |
| 765 | visited.clear(); |
| 766 | state.expand(SRC); |
| 767 | state.expand(WIDGETS); |
| 768 | Tree::new(&model, &state).walk(|row| { |
| 769 | visited.push(row.id); |
| 770 | row.id != SRC |
| 771 | }); |
| 772 | |
| 773 | assert_eq!(visited, vec![SRC, README]); |
| 774 | } |
| 775 | |
| 776 | #[test] |
| 777 | fn selection_moves_over_visible_rows() { |
| 778 | let model = Model::sample(); |
| 779 | let mut state = TreeState::new(); |
| 780 | |
| 781 | state.expand(SRC); |
| 782 | assert!(state.select_nth(&model, 0)); |
| 783 | assert_eq!(state.selected(), Some(SRC)); |
| 784 | assert!(state.select_nth(&model, 2)); |
| 785 | assert_eq!(state.selected(), Some(WIDGETS)); |
| 786 | assert!(state.select_next(&model, 2)); |
| 787 | assert_eq!(state.selected(), Some(README)); |
| 788 | assert!(state.select_next(&model, -99)); |
| 789 | assert_eq!(state.selected(), Some(SRC)); |
| 790 | } |
| 791 | |
| 792 | #[test] |
| 793 | fn select_tracks_anchor_with_cursor() { |
| 794 | let model = Model::sample(); |
| 795 | let mut state = TreeState::new(); |
| 796 | |
| 797 | state.expand(SRC); |
| 798 | state.select(WIDGETS); |
| 799 | assert_eq!(state.anchor(), Some(WIDGETS)); |
| 800 | state.select_next(&model, -1); |
| 801 | assert_eq!(state.anchor(), state.selected()); |
| 802 | state.clear_selection(); |
| 803 | assert_eq!(state.anchor(), None); |
| 804 | } |
| 805 | |
| 806 | #[test] |
| 807 | fn extend_selection_returns_range_in_visible_order() { |
| 808 | let model = Model::sample(); |
| 809 | let mut state = TreeState::new(); |
| 810 | |
| 811 | state.expand(SRC); |
| 812 | state.select(SRC); |
| 813 | |
| 814 | let down = state.extend_selection(&model, 2); |
| 815 | assert_eq!(down, vec![SRC, LIB, WIDGETS]); |
| 816 | assert_eq!(state.anchor(), Some(SRC)); |
| 817 | assert_eq!(state.selected(), Some(WIDGETS)); |
| 818 | |
| 819 | let shrink = state.extend_selection(&model, -1); |
| 820 | assert_eq!(shrink, vec![SRC, LIB]); |
| 821 | assert_eq!(state.anchor(), Some(SRC)); |
| 822 | assert_eq!(state.selected(), Some(LIB)); |
| 823 | |
| 824 | let across = state.extend_selection(&model, 3); |
| 825 | assert_eq!(across, vec![SRC, LIB, WIDGETS, README]); |
| 826 | assert_eq!(state.anchor(), Some(SRC)); |
| 827 | assert_eq!(state.selected(), Some(README)); |
| 828 | } |
| 829 | |
| 830 | #[test] |
| 831 | fn extend_selection_resets_anchor_when_anchor_not_visible() { |
| 832 | let model = Model::sample(); |
| 833 | let mut state = TreeState::new(); |
| 834 | |
| 835 | state.expand(SRC); |
| 836 | state.select(LIB); |
| 837 | // Anchor LIB is hidden after src collapses. |
| 838 | state.collapse(SRC); |
| 839 | |
| 840 | let range = state.extend_selection(&model, 1); |
| 841 | assert_eq!(range.len(), 1); |
| 842 | assert_eq!(state.anchor(), state.selected()); |
| 843 | } |
| 844 | |
| 845 | #[test] |
| 846 | fn toggling_selected_branch_changes_visible_rows() { |
| 847 | let model = Model::sample(); |
| 848 | let mut state = TreeState::new(); |
| 849 | |
| 850 | state.select(SRC); |
| 851 | assert_eq!(state.toggle_selected(&model), Some(TreeNodeState::Expanded)); |
| 852 | assert_eq!(Tree::new(&model, &state).content_rows(), 4); |
| 853 | assert_eq!( |
| 854 | state.toggle_selected(&model), |
| 855 | Some(TreeNodeState::Collapsed) |
| 856 | ); |
| 857 | assert_eq!(Tree::new(&model, &state).content_rows(), 2); |
| 858 | |
| 859 | state.select(README); |
| 860 | assert_eq!(state.toggle_selected(&model), None); |
| 861 | } |
| 862 | |
| 863 | #[test] |
| 864 | fn render_row_indents_markers_and_right_aligns_detail() { |
| 865 | let model = Model::sample(); |
| 866 | let mut state = TreeState::new(); |
| 867 | |
| 868 | state.expand(SRC); |
| 869 | let tree = Tree::new(&model, &state); |
| 870 | let rows = tree.visible_rows(); |
| 871 | |
| 872 | assert_golden( |
| 873 | "tree row rendering", |
| 874 | include_str!("../tests/golden/tree_rows_16x3.txt"), |
| 875 | rows.into_iter() |
| 876 | .take(3) |
| 877 | .map(|row| tree.render_row(row, 16).to_string()) |
| 878 | .collect(), |
| 879 | ); |
| 880 | } |
| 881 | |
| 882 | #[test] |
| 883 | fn selected_row_uses_full_width_style() { |
| 884 | let model = Model::sample(); |
| 885 | let mut state = TreeState::new(); |
| 886 | |
| 887 | state.select(README); |
| 888 | let mut tree = Tree::new(&model, &state); |
| 889 | let mut buffer = Buffer::empty(Rect::new(0, 0, 14, 2)); |
| 890 | |
| 891 | tree.render(buffer.area(), &mut buffer); |
| 892 | |
| 893 | assert_golden( |
| 894 | "selected tree frame", |
| 895 | include_str!("../tests/golden/tree_selected_14x2.txt"), |
| 896 | buffer.lines(), |
| 897 | ); |
| 898 | assert_eq!( |
| 899 | buffer.get(13, 1).map(|cell| cell.style().bg_color()), |
| 900 | Some(Color::Blue) |
| 901 | ); |
| 902 | } |
| 903 | |
| 904 | #[test] |
| 905 | fn tree_rows_scroll_through_scroll_view() { |
| 906 | let model = Model::sample(); |
| 907 | let mut state = TreeState::new(); |
| 908 | |
| 909 | state.expand(SRC); |
| 910 | state.expand(WIDGETS); |
| 911 | let tree = Tree::new(&model, &state); |
| 912 | let rows = tree.visible_rows(); |
| 913 | let mut view = |
| 914 | ScrollView::virtualized(rows.len(), 2, |row, cols| tree.render_row(rows[row], cols)); |
| 915 | let mut buffer = Buffer::empty(Rect::new(0, 0, 22, 2)); |
| 916 | |
| 917 | view.render(buffer.area(), &mut buffer); |
| 918 | |
| 919 | assert_golden( |
| 920 | "scrolled tree rows", |
| 921 | include_str!("../tests/golden/tree_scroll_22x2.txt"), |
| 922 | buffer.lines(), |
| 923 | ); |
| 924 | } |
| 925 | |
| 926 | #[test] |
| 927 | fn hit_test_maps_points_to_visible_rows_and_regions() { |
| 928 | let model = Model::sample(); |
| 929 | let mut state = TreeState::new(); |
| 930 | |
| 931 | state.expand(SRC); |
| 932 | let tree = Tree::new(&model, &state); |
| 933 | let rows = tree.visible_rows(); |
| 934 | let view = View::new(1, rows.len(), 2); |
| 935 | let area = Rect::new(4, 7, 20, 2); |
| 936 | |
| 937 | assert_eq!( |
| 938 | tree.hit_test(&rows, view, area, Point::new(6, 7)), |
| 939 | Some(TreeHit { |
| 940 | row: rows[1], |
| 941 | zone: TreeHitZone::Marker, |
| 942 | }) |
| 943 | ); |
| 944 | assert_eq!( |
| 945 | tree.hit_test(&rows, view, area, Point::new(8, 8)), |
| 946 | Some(TreeHit { |
| 947 | row: rows[2], |
| 948 | zone: TreeHitZone::Content, |
| 949 | }) |
| 950 | ); |
| 951 | assert_eq!(tree.hit_test(&rows, view, area, Point::new(3, 7)), None); |
| 952 | } |
| 953 | } |