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
#![forbid(unsafe_code)]
/*!
Widget built to show Tree Data structures.
Tree widget [`Tree`] is generated with [`TreeItem`s](TreeItem) (which itself can contain [`TreeItem`] children to form the tree structure).
The user interaction state (like the current selection) is stored in the [`TreeState`].
*/
use std::collections::HashSet;
use ratatui::buffer::Buffer;
use ratatui::layout::{Corner, Rect};
use ratatui::style::Style;
use ratatui::text::Text;
use ratatui::widgets::{Block, StatefulWidget, Widget};
use unicode_width::UnicodeWidthStr;
mod flatten;
mod identifier;
pub use crate::flatten::{flatten, Flattened};
pub use crate::identifier::get_without_leaf as get_identifier_without_leaf;
/// Keeps the state of what is currently selected and what was opened in a [`Tree`].
///
/// The generic argument `Identifier` is used to keep the state like the currently selected or opened [`TreeItem`s](TreeItem) in the [`TreeState`].
/// For more information see [`TreeItem`].
///
/// # Example
///
/// ```
/// # use tui_tree_widget::TreeState;
/// type Identifier = usize;
///
/// let mut state = TreeState::<Identifier>::default();
/// ```
#[derive(Debug, Default, Clone)]
pub struct TreeState<Identifier> {
offset: usize,
opened: HashSet<Vec<Identifier>>,
selected: Vec<Identifier>,
}
impl<Identifier> TreeState<Identifier>
where
Identifier: Clone + PartialEq + Eq + core::hash::Hash,
{
#[must_use]
pub const fn get_offset(&self) -> usize {
self.offset
}
#[must_use]
pub fn get_all_opened(&self) -> Vec<Vec<Identifier>> {
self.opened.iter().cloned().collect()
}
#[must_use]
pub fn selected(&self) -> Vec<Identifier> {
self.selected.clone()
}
pub fn select(&mut self, identifier: Vec<Identifier>) {
self.selected = identifier;
// TODO: ListState does this. Is this relevant?
if self.selected.is_empty() {
self.offset = 0;
}
}
/// Open a tree node.
/// Returns `true` if the node was closed and has been opened.
/// Returns `false` if the node was already open.
pub fn open(&mut self, identifier: Vec<Identifier>) -> bool {
if identifier.is_empty() {
false
} else {
self.opened.insert(identifier)
}
}
/// Close a tree node.
/// Returns `true` if the node was open and has been closed.
/// Returns `false` if the node was already closed.
pub fn close(&mut self, identifier: &[Identifier]) -> bool {
self.opened.remove(identifier)
}
/// Toggles a tree node.
/// If the node is in opened then it calls `close()`. Otherwise it calls `open()`.
pub fn toggle(&mut self, identifier: Vec<Identifier>) {
if self.opened.contains(&identifier) {
self.close(&identifier);
} else {
self.open(identifier);
}
}
/// Toggles the currently selected tree node.
/// See also [`toggle`](TreeState::toggle)
pub fn toggle_selected(&mut self) {
self.toggle(self.selected());
}
pub fn close_all(&mut self) {
self.opened.clear();
}
/// Select the first node.
pub fn select_first(&mut self, items: &[TreeItem<Identifier>]) {
let identifier = items
.first()
.map(|o| vec![o.identifier.clone()])
.unwrap_or_default();
self.select(identifier);
}
/// Select the last visible node.
pub fn select_last(&mut self, items: &[TreeItem<Identifier>]) {
let visible = flatten(&self.get_all_opened(), items);
let new_identifier = visible
.last()
.map(|o| o.identifier.clone())
.unwrap_or_default();
self.select(new_identifier);
}
/// Select the node visible on the given index.
///
/// Returns `true` when the selection changed.
///
/// This can be useful for mouse clicks.
pub fn select_visible_index(
&mut self,
items: &[TreeItem<Identifier>],
new_index: usize,
) -> bool {
let current_identifier = self.selected();
let visible = flatten(&self.get_all_opened(), items);
let new_index = new_index.min(visible.len().saturating_sub(1));
let new_identifier = visible
.get(new_index)
.map(|o| o.identifier.clone())
.unwrap_or_default();
let changed = current_identifier != new_identifier;
self.select(new_identifier);
changed
}
/// Move the current selection with the direction/amount by the given function.
///
/// Returns `true` when the selection changed.
///
/// # Example
///
/// ```
/// # use tui_tree_widget::TreeState;
/// # let items = vec![];
/// # type Identifier = usize;
/// # let mut state = TreeState::<Identifier>::default();
/// // Move the selection one down
/// state.select_visible_relative(&items, |current| {
/// current.map_or(0, |current| current.saturating_add(1))
/// });
/// ```
///
/// For more examples take a look into the source code of [`TreeState::key_up`] or [`TreeState::key_down`].
/// They are implemented with this method.
pub fn select_visible_relative<F>(&mut self, items: &[TreeItem<Identifier>], f: F) -> bool
where
F: FnOnce(Option<usize>) -> usize,
{
let visible = flatten(&self.get_all_opened(), items);
let current_identifier = self.selected();
let current_index = visible
.iter()
.position(|o| o.identifier == current_identifier);
let new_index = f(current_index).min(visible.len().saturating_sub(1));
let new_identifier = visible
.get(new_index)
.map(|o| o.identifier.clone())
.unwrap_or_default();
let changed = current_index != Some(new_index);
self.select(new_identifier);
changed
}
/// Handles the up arrow key.
/// Moves up in the current depth or to its parent.
pub fn key_up(&mut self, items: &[TreeItem<Identifier>]) {
self.select_visible_relative(items, |current| {
current.map_or(usize::MAX, |current| current.saturating_sub(1))
});
}
/// Handles the down arrow key.
/// Moves down in the current depth or into a child node.
pub fn key_down(&mut self, items: &[TreeItem<Identifier>]) {
self.select_visible_relative(items, |current| {
current.map_or(0, |current| current.saturating_add(1))
});
}
/// Handles the left arrow key.
/// Closes the currently selected or moves to its parent.
pub fn key_left(&mut self) {
let selected = self.selected();
if !self.close(&selected) {
let (head, _) = get_identifier_without_leaf(&selected);
self.select(head.to_vec());
}
}
/// Handles the right arrow key.
/// Opens the currently selected.
pub fn key_right(&mut self) {
self.open(self.selected());
}
}
/// One item inside a [`Tree`].
///
/// Can have zero or more `children`.
///
/// # Identifier
///
/// The generic argument `Identifier` is used to keep the state like the currently selected or opened [`TreeItem`s](TreeItem) in the [`TreeState`].
///
/// It needs to be unique among its siblings but can be used again on parent or child [`TreeItem`s](TreeItem).
/// A common example would be a filename which has to be unique in its directory while it can exist in another.
///
/// The `text` can be different from its `identifier`.
/// To repeat the filename analogy: File browsers sometimes hide file extensions.
/// The filename `main.rs` is the identifier while its shown as `main`.
/// Two files `main.rs` and `main.toml` can exist in the same directory and can both be displayed as `main` but their identifier is different.
///
/// Just like every file in a file system can be uniquely identified with its file and directory names each [`TreeItem`] in a [`Tree`] can be with these identifiers.
/// As an example the following two identifiers describe the main file in a Rust cargo project: `vec!["src", "main.rs"]`.
///
/// The identifier does not need to be a `String` and is therefore generic.
/// Until version 0.14 this crate used `usize` and indices.
/// This might still be perfect for your use case.
///
/// # Example
///
/// ```
/// # use tui_tree_widget::TreeItem;
/// let a = TreeItem::new_leaf("l", "Leaf");
/// let b = TreeItem::new("r", "Root", vec![a])?;
/// # Ok::<(), std::io::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct TreeItem<'a, Identifier> {
identifier: Identifier,
text: Text<'a>,
style: Style,
children: Vec<TreeItem<'a, Identifier>>,
}
impl<'a, Identifier> TreeItem<'a, Identifier>
where
Identifier: Clone + PartialEq + Eq + core::hash::Hash,
{
/// Create a new `TreeItem` without children.
#[must_use]
pub fn new_leaf<T>(identifier: Identifier, text: T) -> Self
where
T: Into<Text<'a>>,
{
Self {
identifier,
text: text.into(),
style: Style::new(),
children: Vec::new(),
}
}
/// Create a new `TreeItem` with children.
///
/// # Errors
///
/// Errors when there are duplicate identifiers in the children.
pub fn new<T>(
identifier: Identifier,
text: T,
children: Vec<TreeItem<'a, Identifier>>,
) -> std::io::Result<Self>
where
T: Into<Text<'a>>,
{
let identifiers = children
.iter()
.map(|o| &o.identifier)
.collect::<HashSet<_>>();
if identifiers.len() != children.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
"The children contain duplicate identifiers",
));
}
Ok(Self {
identifier,
text: text.into(),
style: Style::new(),
children,
})
}
#[must_use]
pub fn children(&self) -> &[TreeItem<Identifier>] {
&self.children
}
/// Get a reference to a child by index.
#[must_use]
pub fn child(&self, index: usize) -> Option<&Self> {
self.children.get(index)
}
/// Get a mutable reference to a child by index.
///
/// When you choose to change the `identifier` the [`TreeState`] might not work as expected afterwards.
#[must_use]
pub fn child_mut(&mut self, index: usize) -> Option<&mut Self> {
self.children.get_mut(index)
}
#[must_use]
pub fn height(&self) -> usize {
self.text.height()
}
#[must_use]
pub const fn style(mut self, style: Style) -> Self {
self.style = style;
self
}
/// Add a child to the `TreeItem`.
///
/// # Errors
///
/// Errors when the `identifier` of the `child` already exists in the children.
pub fn add_child(&mut self, child: TreeItem<'a, Identifier>) -> std::io::Result<()> {
let existing = self
.children
.iter()
.map(|o| &o.identifier)
.collect::<HashSet<_>>();
if existing.contains(&child.identifier) {
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
"identifier already exists in the children",
));
}
self.children.push(child);
Ok(())
}
}
#[test]
#[should_panic = "duplicate identifiers"]
fn tree_item_new_errors_with_duplicate_identifiers() {
let a = TreeItem::new_leaf("same", "text");
let b = a.clone();
TreeItem::new("root", "Root", vec![a, b]).unwrap();
}
#[test]
#[should_panic = "identifier already exists"]
fn tree_item_add_child_errors_with_duplicate_identifiers() {
let a = TreeItem::new_leaf("same", "text");
let b = a.clone();
let mut root = TreeItem::new("root", "Root", vec![a]).unwrap();
root.add_child(b).unwrap();
}
/// A `Tree` which can be rendered.
///
/// The generic argument `Identifier` is used to keep the state like the currently selected or opened [`TreeItem`s](TreeItem) in the [`TreeState`].
/// For more information see [`TreeItem`].
///
/// # Example
///
/// ```
/// # use tui_tree_widget::{Tree, TreeItem, TreeState};
/// # use ratatui::backend::TestBackend;
/// # use ratatui::Terminal;
/// # use ratatui::widgets::{Block, Borders};
/// # let mut terminal = Terminal::new(TestBackend::new(32, 32)).unwrap();
/// let mut state = TreeState::default();
///
/// let item = TreeItem::new_leaf("l", "leaf");
/// let items = vec![item];
///
/// terminal.draw(|f| {
/// let area = f.size();
///
/// let tree_widget = Tree::new(items)
/// .expect("all item identifiers are unique")
/// .block(Block::new().borders(Borders::ALL).title("Tree Widget"));
///
/// f.render_stateful_widget(tree_widget, area, &mut state);
/// })?;
/// # Ok::<(), std::io::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct Tree<'a, Identifier> {
items: Vec<TreeItem<'a, Identifier>>,
block: Option<Block<'a>>,
start_corner: Corner,
/// Style used as a base style for the widget
style: Style,
/// Style used to render selected item
highlight_style: Style,
/// Symbol in front of the selected item (Shift all items to the right)
highlight_symbol: &'a str,
/// Symbol displayed in front of a closed node (As in the children are currently not visible)
node_closed_symbol: &'a str,
/// Symbol displayed in front of an open node. (As in the children are currently visible)
node_open_symbol: &'a str,
/// Symbol displayed in front of a node without children.
node_no_children_symbol: &'a str,
}
impl<'a, Identifier> Tree<'a, Identifier>
where
Identifier: Clone + PartialEq + Eq + core::hash::Hash,
{
/// Create a new `Tree`.
///
/// # Errors
///
/// Errors when there are duplicate identifiers in the children.
pub fn new(items: Vec<TreeItem<'a, Identifier>>) -> std::io::Result<Self> {
let identifiers = items.iter().map(|o| &o.identifier).collect::<HashSet<_>>();
if identifiers.len() != items.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
"The items contain duplicate identifiers",
));
}
Ok(Self {
items,
block: None,
start_corner: Corner::TopLeft,
style: Style::new(),
highlight_style: Style::new(),
highlight_symbol: "",
node_closed_symbol: "\u{25b6} ", // Arrow to right
node_open_symbol: "\u{25bc} ", // Arrow down
node_no_children_symbol: " ",
})
}
#[allow(clippy::missing_const_for_fn)]
#[must_use]
pub fn block(mut self, block: Block<'a>) -> Self {
self.block = Some(block);
self
}
#[must_use]
pub const fn start_corner(mut self, corner: Corner) -> Self {
self.start_corner = corner;
self
}
#[must_use]
pub const fn style(mut self, style: Style) -> Self {
self.style = style;
self
}
#[must_use]
pub const fn highlight_style(mut self, style: Style) -> Self {
self.highlight_style = style;
self
}
#[must_use]
pub const fn highlight_symbol(mut self, highlight_symbol: &'a str) -> Self {
self.highlight_symbol = highlight_symbol;
self
}
#[must_use]
pub const fn node_closed_symbol(mut self, symbol: &'a str) -> Self {
self.node_closed_symbol = symbol;
self
}
#[must_use]
pub const fn node_open_symbol(mut self, symbol: &'a str) -> Self {
self.node_open_symbol = symbol;
self
}
#[must_use]
pub const fn node_no_children_symbol(mut self, symbol: &'a str) -> Self {
self.node_no_children_symbol = symbol;
self
}
}
#[test]
#[should_panic = "duplicate identifiers"]
fn tree_new_errors_with_duplicate_identifiers() {
let a = TreeItem::new_leaf("same", "text");
let b = a.clone();
Tree::new(vec![a, b]).unwrap();
}
impl<'a, Identifier> StatefulWidget for Tree<'a, Identifier>
where
Identifier: Clone + PartialEq + Eq + core::hash::Hash,
{
type State = TreeState<Identifier>;
#[allow(clippy::too_many_lines)]
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
buf.set_style(area, self.style);
// Get the inner area inside a possible block, otherwise use the full area
let area = self.block.map_or(area, |b| {
let inner_area = b.inner(area);
b.render(area, buf);
inner_area
});
if area.width < 1 || area.height < 1 {
return;
}
let visible = flatten(&state.get_all_opened(), &self.items);
if visible.is_empty() {
return;
}
let available_height = area.height as usize;
let selected_index = if state.selected.is_empty() {
0
} else {
visible
.iter()
.position(|o| o.identifier == state.selected)
.unwrap_or(0)
};
let mut start = state.offset.min(selected_index);
let mut end = start;
let mut height = 0;
for item in visible.iter().skip(start) {
if height + item.item.height() > available_height {
break;
}
height += item.item.height();
end += 1;
}
while selected_index >= end {
height = height.saturating_add(visible[end].item.height());
end += 1;
while height > available_height {
height = height.saturating_sub(visible[start].item.height());
start += 1;
}
}
state.offset = start;
let blank_symbol = " ".repeat(self.highlight_symbol.width());
let mut current_height = 0;
let has_selection = !state.selected.is_empty();
#[allow(clippy::cast_possible_truncation)]
for item in visible.iter().skip(state.offset).take(end - start) {
#[allow(clippy::single_match_else)] // Keep same as List impl
let (x, y) = match self.start_corner {
Corner::BottomLeft => {
current_height += item.item.height() as u16;
(area.left(), area.bottom() - current_height)
}
_ => {
let pos = (area.left(), area.top() + current_height);
current_height += item.item.height() as u16;
pos
}
};
let area = Rect {
x,
y,
width: area.width,
height: item.item.height() as u16,
};
let item_style = self.style.patch(item.item.style);
buf.set_style(area, item_style);
let is_selected = state.selected == item.identifier;
let after_highlight_symbol_x = if has_selection {
let symbol = if is_selected {
self.highlight_symbol
} else {
&blank_symbol
};
let (x, _) = buf.set_stringn(x, y, symbol, area.width as usize, item_style);
x
} else {
x
};
let after_depth_x = {
let indent_width = item.depth() * 2;
let (after_indent_x, _) = buf.set_stringn(
after_highlight_symbol_x,
y,
" ".repeat(indent_width),
indent_width,
item_style,
);
let symbol = if item.item.children.is_empty() {
self.node_no_children_symbol
} else if state.opened.contains(&item.identifier) {
self.node_open_symbol
} else {
self.node_closed_symbol
};
let max_width = area.width.saturating_sub(after_indent_x - x);
let (x, _) =
buf.set_stringn(after_indent_x, y, symbol, max_width as usize, item_style);
x
};
let max_element_width = area.width.saturating_sub(after_depth_x - x);
for (j, line) in item.item.text.lines.iter().enumerate() {
buf.set_line(after_depth_x, y + j as u16, line, max_element_width);
}
if is_selected {
buf.set_style(area, self.highlight_style);
}
}
}
}
impl<'a, Identifier> Widget for Tree<'a, Identifier>
where
Identifier: Clone + Default + Eq + core::hash::Hash,
{
fn render(self, area: Rect, buf: &mut Buffer) {
let mut state = TreeState::default();
StatefulWidget::render(self, area, buf, &mut state);
}
}