#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TreeNode {
pub id: String,
pub label: String,
pub node_type: String,
pub icon: Option<String>,
pub children: Vec<TreeNode>,
pub expanded: bool,
pub checked: bool,
pub metadata: Option<String>,
}
impl TreeNode {
pub fn new(
id: impl Into<String>,
label: impl Into<String>,
node_type: impl Into<String>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
node_type: node_type.into(),
icon: None,
children: Vec::new(),
expanded: false,
checked: false,
metadata: None,
}
}
pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn with_children(mut self, children: Vec<TreeNode>) -> Self {
self.children = children;
self
}
pub fn with_expanded(mut self, expanded: bool) -> Self {
self.expanded = expanded;
self
}
pub fn with_checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
pub fn with_metadata(mut self, metadata: impl Into<String>) -> Self {
self.metadata = Some(metadata.into());
self
}
pub fn find(&self, id: &str) -> Option<&TreeNode> {
if self.id == id {
return Some(self);
}
for child in &self.children {
if let Some(found) = child.find(id) {
return Some(found);
}
}
None
}
pub fn find_mut(&mut self, id: &str) -> Option<&mut TreeNode> {
if self.id == id {
return Some(self);
}
for child in &mut self.children {
if let Some(found) = child.find_mut(id) {
return Some(found);
}
}
None
}
pub fn all_ids(&self) -> Vec<String> {
let mut ids = vec![self.id.clone()];
for child in &self.children {
ids.extend(child.all_ids());
}
ids
}
pub fn checked_ids(&self) -> Vec<String> {
let mut ids = Vec::new();
if self.checked {
ids.push(self.id.clone());
}
for child in &self.children {
ids.extend(child.checked_ids());
}
ids
}
pub fn has_children(&self) -> bool {
!self.children.is_empty()
}
pub fn depth(&self) -> usize {
if self.children.is_empty() {
0
} else {
1 + self.children.iter().map(|c| c.depth()).max().unwrap_or(0)
}
}
}