tui_tree_widget/
tree_item.rs

1use std::collections::HashSet;
2
3use ratatui_core::text::Text;
4
5/// One item inside a [`Tree`](crate::Tree).
6///
7/// Can have zero or more `children`.
8///
9/// # Identifier
10///
11/// The generic argument `Identifier` is used to keep the state like the currently selected or opened [`TreeItem`]s in the [`TreeState`](crate::TreeState).
12///
13/// It needs to be unique among its siblings but can be used again on parent or child [`TreeItem`]s.
14/// A common example would be a filename which has to be unique in its directory while it can exist in another.
15///
16/// The `text` can be different from its `identifier`.
17/// To repeat the filename analogy: File browsers sometimes hide file extensions.
18/// The filename `main.rs` is the identifier while its shown as `main`.
19/// 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.
20///
21/// Just like every file in a file system can be uniquely identified with its file and directory names each [`TreeItem`] in a [`Tree`](crate::Tree) can be with these identifiers.
22/// As an example the following two identifiers describe the main file in a Rust cargo project: `vec!["src", "main.rs"]`.
23///
24/// The identifier does not need to be a `String` and is therefore generic.
25/// Until version 0.14 this crate used `usize` and indices.
26/// This might still be perfect for your use case.
27///
28/// # Example
29///
30/// ```
31/// # use tui_tree_widget::TreeItem;
32/// let a = TreeItem::new_leaf("l", "Leaf");
33/// let b = TreeItem::new("r", "Root", vec![a])?;
34/// # Ok::<(), std::io::Error>(())
35/// ```
36#[derive(Debug, Clone)]
37pub struct TreeItem<'text, Identifier> {
38    pub(super) identifier: Identifier,
39    pub(super) text: Text<'text>,
40    pub(super) children: Vec<Self>,
41}
42
43impl<'text, Identifier> TreeItem<'text, Identifier>
44where
45    Identifier: Clone + PartialEq + Eq + core::hash::Hash,
46{
47    /// Create a new `TreeItem` without children.
48    #[must_use]
49    pub fn new_leaf<T>(identifier: Identifier, text: T) -> Self
50    where
51        T: Into<Text<'text>>,
52    {
53        Self {
54            identifier,
55            text: text.into(),
56            children: Vec::new(),
57        }
58    }
59
60    /// Create a new `TreeItem` with children.
61    ///
62    /// # Errors
63    ///
64    /// Errors when there are duplicate identifiers in the children.
65    pub fn new<T>(identifier: Identifier, text: T, children: Vec<Self>) -> std::io::Result<Self>
66    where
67        T: Into<Text<'text>>,
68    {
69        let identifiers = children
70            .iter()
71            .map(|item| &item.identifier)
72            .collect::<HashSet<_>>();
73        if identifiers.len() != children.len() {
74            return Err(std::io::Error::new(
75                std::io::ErrorKind::AlreadyExists,
76                "The children contain duplicate identifiers",
77            ));
78        }
79
80        Ok(Self {
81            identifier,
82            text: text.into(),
83            children,
84        })
85    }
86
87    /// Get a reference to the identifier.
88    #[must_use]
89    pub const fn identifier(&self) -> &Identifier {
90        &self.identifier
91    }
92
93    #[must_use]
94    pub fn children(&self) -> &[Self] {
95        &self.children
96    }
97
98    /// Get a reference to a child by index.
99    #[must_use]
100    pub fn child(&self, index: usize) -> Option<&Self> {
101        self.children.get(index)
102    }
103
104    /// Get a mutable reference to a child by index.
105    ///
106    /// When you choose to change the `identifier` the [`TreeState`](crate::TreeState) might not work as expected afterwards.
107    #[must_use]
108    pub fn child_mut(&mut self, index: usize) -> Option<&mut Self> {
109        self.children.get_mut(index)
110    }
111
112    #[must_use]
113    pub fn height(&self) -> usize {
114        self.text.height()
115    }
116
117    /// Add a child to the `TreeItem`.
118    ///
119    /// # Errors
120    ///
121    /// Errors when the `identifier` of the `child` already exists in the children.
122    pub fn add_child(&mut self, child: Self) -> std::io::Result<()> {
123        let existing = self
124            .children
125            .iter()
126            .map(|item| &item.identifier)
127            .collect::<HashSet<_>>();
128        if existing.contains(&child.identifier) {
129            return Err(std::io::Error::new(
130                std::io::ErrorKind::AlreadyExists,
131                "identifier already exists in the children",
132            ));
133        }
134
135        self.children.push(child);
136        Ok(())
137    }
138}
139
140impl TreeItem<'static, &'static str> {
141    #[cfg(test)]
142    #[must_use]
143    pub(crate) fn example() -> Vec<Self> {
144        vec![
145            Self::new_leaf("a", "Alfa"),
146            Self::new(
147                "b",
148                "Bravo",
149                vec![
150                    Self::new_leaf("c", "Charlie"),
151                    Self::new(
152                        "d",
153                        "Delta",
154                        vec![Self::new_leaf("e", "Echo"), Self::new_leaf("f", "Foxtrot")],
155                    )
156                    .expect("all item identifiers are unique"),
157                    Self::new_leaf("g", "Golf"),
158                ],
159            )
160            .expect("all item identifiers are unique"),
161            Self::new_leaf("h", "Hotel"),
162        ]
163    }
164}
165
166#[test]
167#[should_panic = "duplicate identifiers"]
168fn tree_item_new_errors_with_duplicate_identifiers() {
169    let item = TreeItem::new_leaf("same", "text");
170    let another = item.clone();
171    TreeItem::new("root", "Root", vec![item, another]).unwrap();
172}
173
174#[test]
175#[should_panic = "identifier already exists"]
176fn tree_item_add_child_errors_with_duplicate_identifiers() {
177    let item = TreeItem::new_leaf("same", "text");
178    let another = item.clone();
179    let mut root = TreeItem::new("root", "Root", vec![item]).unwrap();
180    root.add_child(another).unwrap();
181}