Something went wrong. Try again.
A simple TUI Library written in Rust
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118use crate::block::Block;use crate::style::{Line, Span};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum NodeState { Pending, Running, Done, Failed, Skipped,}
impl NodeState { pub fn icon(&self) -> &'static str { match self { NodeState::Pending => "○", NodeState::Running => "◌", NodeState::Done => "✓", NodeState::Failed => "✗", NodeState::Skipped => "–", } }}
#[derive(Debug, Clone)]pub struct TreeNode { pub label: Line, pub children: Vec<TreeNode>, pub state: NodeState,}
impl TreeNode { /// Create a leaf node with the given label and state. pub fn new(label: Line, state: NodeState) -> Self { TreeNode { label, children: vec![], state, } }
/// Create a node with children. pub fn with_children(label: Line, state: NodeState, children: Vec<TreeNode>) -> Self { TreeNode { label, children, state, } }}
/// Render a forest (list of nodes) as a Block.pub fn to_block(nodes: &[TreeNode]) -> Block { let lines = render_forest(nodes, ""); Block::text(lines)}
fn render_forest(nodes: &[TreeNode], prefix: &str) -> Vec<Line> { let total = nodes.len(); let mut result = Vec::new(); for (i, node) in nodes.iter().enumerate() { let is_last = i == total - 1; let connector = if is_last { "└─ " } else { "├─ " }; let child_prefix = if is_last { format!("{prefix} ") } else { format!("{prefix}│ ") }; let icon = node.state.icon(); let mut node_line = vec![Span::plain(format!("{prefix}{connector}{icon} "))]; node_line.extend(node.label.iter().cloned()); result.push(node_line); if !node.children.is_empty() { result.extend(render_forest(&node.children, &child_prefix)); } } result}
#[cfg(test)]mod tests { use super::*;
#[test] fn single_node_renders() { let nodes = vec![TreeNode::new(vec![Span::plain("test")], NodeState::Done)]; let block = to_block(&nodes); let lines = block.render(30); assert_eq!(lines.len(), 1); assert!(lines[0].contains("✓")); assert!(lines[0].contains("test")); }
#[test] fn nested_nodes() { let nodes = vec![TreeNode::with_children( vec![Span::plain("parent")], NodeState::Running, vec![ TreeNode::new(vec![Span::plain("child1")], NodeState::Done), TreeNode::new(vec![Span::plain("child2")], NodeState::Pending), ], )]; let block = to_block(&nodes); let lines = block.render(40); assert_eq!(lines.len(), 3); }
#[test] fn state_icons() { assert_eq!(NodeState::Pending.icon(), "○"); assert_eq!(NodeState::Running.icon(), "◌"); assert_eq!(NodeState::Done.icon(), "✓"); assert_eq!(NodeState::Failed.icon(), "✗"); assert_eq!(NodeState::Skipped.icon(), "–"); }}