Skip to main content

zaxis/components/tree_view/
model.rs

1use crate::{Id, ImageSource};
2
3/// Unloaded/loading/error remain branches even with no known children.
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum TreeChildren {
6    Leaf,
7    Unloaded,
8    Loading,
9    Loaded,
10    Error,
11}
12impl TreeChildren {
13    pub fn expandable(self) -> bool {
14        self != Self::Leaf
15    }
16}
17#[derive(Clone, Copy, Debug)]
18pub struct TreeNode<'a> {
19    pub label: &'a str,
20    pub icon: Option<&'a ImageSource>,
21    pub enabled: bool,
22    pub children: TreeChildren,
23}
24impl<'a> TreeNode<'a> {
25    pub fn leaf(label: &'a str) -> Self {
26        Self {
27            label,
28            icon: None,
29            enabled: true,
30            children: TreeChildren::Leaf,
31        }
32    }
33    pub fn branch(label: &'a str) -> Self {
34        Self {
35            children: TreeChildren::Loaded,
36            ..Self::leaf(label)
37        }
38    }
39    pub fn icon(mut self, icon: &'a ImageSource) -> Self {
40        self.icon = Some(icon);
41        self
42    }
43    pub fn enabled(mut self, enabled: bool) -> Self {
44        self.enabled = enabled;
45        self
46    }
47    pub fn children(mut self, children: TreeChildren) -> Self {
48        self.children = children;
49        self
50    }
51}
52/// Application-owned model. Ids are globally unique within this tree.
53/// `node` must look up hidden nodes too; None means deleted, never offscreen.
54/// Increment revision for topology, enabled, loading, label or icon changes.
55pub trait TreeModel {
56    fn revision(&self) -> u64;
57    fn roots(&self) -> impl Iterator<Item = Id>;
58    fn children(&self, node: Id) -> impl Iterator<Item = Id>;
59    fn node(&self, node: Id) -> Option<TreeNode<'_>>;
60    /// Required for reveal and optimal hidden-focus repair. Must be direct lookup.
61    fn parent(&self, _node: Id) -> Option<Id> {
62        None
63    }
64}
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub enum TreeEvent {
67    OpenChanged {
68        node: Id,
69        open: bool,
70    },
71    Selected {
72        node: Option<Id>,
73    },
74    Activated {
75        node: Id,
76    },
77    ContextAction {
78        node: Id,
79    },
80    RequestChildren {
81        node: Id,
82    },
83    /// A drag finished: move `node` relative to `target`. The application edits
84    /// its model and bumps the revision.
85    Moved {
86        node: Id,
87        target: Id,
88        position: crate::Insertion,
89    },
90}
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum TreeIssue {
93    DuplicateOrCycle(Id),
94    MissingNode(Id),
95    InvalidRevealPath(Id),
96}