Skip to main content

slint_tree_view/
lib.rs

1#![deny(unsafe_code)]
2
3/// Sentinel for an item with no parent (top-level). Used as the
4/// `parent-internal-id` of root items.
5pub const NO_PARENT: i32 = -1;
6
7/// Generated Slint types live under this submodule so the consumer's
8/// slint-compiler can find them at `slint_tree_view::tree_view::*` (the
9/// path advertised by `rust_module("tree_view")` in `build.rs`).
10//
11// Slint's generated code uses `unsafe` for its vtable plumbing, so we
12// locally allow it here — the deny-at-crate-root above still catches any
13// hand-written `unsafe` elsewhere in the crate.
14#[allow(unsafe_code)]
15pub mod tree_view {
16    slint::include_modules!();
17}
18
19// Convenience re-exports at the crate root.
20pub use tree_view::{ActivationMode, TreeItem, TreeView, TreeViewStyle};
21
22/// Convenience constructors for [`TreeItem`], pre-populating the fields
23/// a typical host wants for each structural kind. The view itself stays
24/// agnostic — `branch()` / `leaf()` / `section()` just save you writing
25/// 11-field struct literals.
26///
27/// Naming: these use **structural** CS tree terms, not domain terms. The
28/// view never knows whether an item is a "folder" or a "file" — that's
29/// the host's call. So the constructors are named after the item's
30/// *structural* role in the tree (branch = has children, leaf =
31/// doesn't), and the host layers domain semantics (folder / mailbox /
32/// project / category) on top via `item-type` and `decoration-text`.
33impl TreeItem {
34    /// A branch item — a node that holds children. `expanded` defaults
35    /// to true (matches the "everything visible" convention most apps
36    /// start with); pass `.collapsed()` for a collapsed branch.
37    pub fn branch(
38        internal_id: i32,
39        parent_internal_id: i32,
40        depth: i32,
41        text: impl Into<slint::SharedString>,
42    ) -> Self {
43        Self {
44            internal_id,
45            parent_internal_id,
46            depth,
47            text: text.into(),
48            label: "".into(),
49            decoration_text: "".into(),
50            item_type: 0,
51            user_data: String::new().into(),
52            has_children: true,
53            expanded: true,
54            selectable: true,
55            enabled: true,
56        }
57    }
58
59    /// A leaf item — a node with no children. `user-data` is the opaque
60    /// payload the host can read back via `model[current-index]`; the
61    /// view never interprets it.
62    pub fn leaf(
63        internal_id: i32,
64        parent_internal_id: i32,
65        depth: i32,
66        text: impl Into<slint::SharedString>,
67        user_data: impl Into<slint::SharedString>,
68    ) -> Self {
69        Self {
70            internal_id,
71            parent_internal_id,
72            depth,
73            text: text.into(),
74            label: "".into(),
75            decoration_text: "".into(),
76            item_type: 0,
77            user_data: user_data.into(),
78            has_children: false,
79            expanded: false,
80            selectable: true,
81            enabled: true,
82        }
83    }
84
85    /// A non-selectable section header / separator. Visible but skipped
86    /// by mouse selection and `current-changed`. Useful for grouping
87    /// items under a category label.
88    pub fn section(
89        internal_id: i32,
90        parent_internal_id: i32,
91        depth: i32,
92        text: impl Into<slint::SharedString>,
93    ) -> Self {
94        Self {
95            internal_id,
96            parent_internal_id,
97            depth,
98            text: text.into(),
99            label: "".into(),
100            decoration_text: "".into(),
101            item_type: 0,
102            user_data: String::new().into(),
103            has_children: false,
104            expanded: false,
105            // Sections are visible but not selectable.
106            selectable: false,
107            enabled: true,
108        }
109    }
110
111    // ---- Builder methods (fluent overrides on the above defaults) ----
112
113    /// Chain a decoration glyph onto an item (any of the constructors
114    /// above). Alias of [`with_decoration`](Self::with_decoration).
115    pub fn with_icon(self, icon: impl Into<slint::SharedString>) -> Self {
116        self.with_decoration(icon)
117    }
118
119    /// Chain an accessible label used by screen readers onto an item.
120    pub fn with_label(mut self, label: impl Into<slint::SharedString>) -> Self {
121        self.label = label.into();
122        self
123    }
124
125    /// Chain an arbitrary decoration string (the icon/glyph shown before
126    /// the item's text).
127    pub fn with_decoration(mut self, decoration: impl Into<slint::SharedString>) -> Self {
128        self.decoration_text = decoration.into();
129        self
130    }
131
132    /// Override the default `expanded = true` on a branch.
133    pub fn collapsed(mut self) -> Self {
134        self.expanded = false;
135        self
136    }
137
138    /// Set `expanded` explicitly.
139    pub fn with_expanded(mut self, expanded: bool) -> Self {
140        self.expanded = expanded;
141        self
142    }
143
144    /// Mark the item disabled (greyed out, ignored by mouse & keyboard).
145    pub fn disabled(mut self) -> Self {
146        self.enabled = false;
147        self
148    }
149
150    /// Mark the item non-selectable (visible, but `current-changed` is
151    /// not emitted for it).
152    pub fn non_selectable(mut self) -> Self {
153        self.selectable = false;
154        self
155    }
156
157    /// Set the application-defined `item-type` discriminator (lets the
158    /// host distinguish folder/file/clip/whatever — the view doesn't
159    /// interpret it).
160    pub fn with_item_type(mut self, item_type: i32) -> Self {
161        self.item_type = item_type;
162        self
163    }
164
165    /// Set the opaque `user-data` payload (the host can read it back from
166    /// `model[current-index]`; the view never does).
167    pub fn with_user_data(mut self, user_data: impl Into<slint::SharedString>) -> Self {
168        self.user_data = user_data.into();
169        self
170    }
171}
172
173// ---- Free-function helpers (the host does a lot of id↔index math) ----
174
175/// Find the index of the first item with the given `internal-id`, or
176/// `None`. Hosts need this constantly when handling TreeView callbacks
177/// (which report ids) against their own `Vec<TreeItem>`.
178pub fn index_of_id(items: &[TreeItem], internal_id: i32) -> Option<usize> {
179    items.iter().position(|r| r.internal_id == internal_id)
180}
181
182/// Same lookup against a Slint `ModelRc<TreeItem>` (what `TreeView`'s
183/// `get_model()` returns). The linear walk is fine for typical trees
184/// (≤ a few thousand items); for huge trees the host should maintain its
185/// own `HashMap<i32, usize>` side index.
186pub fn index_of_id_model(model: &slint::ModelRc<TreeItem>, internal_id: i32) -> Option<usize> {
187    use slint::Model as _;
188    (0..model.row_count()).find(|&i| {
189        model
190            .row_data(i)
191            .is_some_and(|r| r.internal_id == internal_id)
192    })
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn default_is_blank_leaf() {
201        // Slint-derived Default: bool fields default to false. So a raw
202        // `TreeItem::default()` is a non-selectable disabled leaf — hosts
203        // should reach for the named constructors instead.
204        let item = TreeItem::default();
205        assert_eq!(item.depth, 0);
206        assert_eq!(item.internal_id, 0);
207        assert_eq!(item.parent_internal_id, 0);
208        assert!(!item.has_children);
209        assert!(!item.expanded);
210    }
211
212    #[test]
213    fn branch_constructor_marks_has_children_and_expanded() {
214        let item = TreeItem::branch(7, NO_PARENT, 0, "Inbox");
215        assert_eq!(item.internal_id, 7);
216        assert_eq!(item.parent_internal_id, NO_PARENT);
217        assert_eq!(item.depth, 0);
218        assert_eq!(item.text.as_str(), "Inbox");
219        assert!(item.has_children);
220        assert!(item.expanded, "branches default to expanded");
221        assert!(item.selectable);
222        assert!(item.enabled);
223        assert_eq!(
224            item.decoration_text.as_str(),
225            "",
226            "no default decoration — host decides"
227        );
228    }
229
230    #[test]
231    fn leaf_constructor_marks_no_children() {
232        let item = TreeItem::leaf(3, 7, 1, "Welcome", "Hello world");
233        assert_eq!(item.internal_id, 3);
234        assert_eq!(item.parent_internal_id, 7);
235        assert_eq!(item.depth, 1);
236        assert_eq!(item.user_data.as_str(), "Hello world");
237        assert!(!item.has_children);
238        assert!(!item.expanded);
239    }
240
241    #[test]
242    fn section_constructor_is_non_selectable() {
243        let item = TreeItem::section(100, NO_PARENT, 0, "Archived");
244        assert!(!item.selectable, "sections are skipped by selection");
245        assert!(item.enabled, "sections are still visible/enabled");
246        assert!(!item.has_children);
247    }
248
249    #[test]
250    fn builder_methods_chain() {
251        let item = TreeItem::branch(1, NO_PARENT, 0, "Inbox")
252            .with_icon("📥")
253            .collapsed()
254            .with_item_type(42);
255        assert_eq!(item.decoration_text.as_str(), "📥");
256        assert!(!item.expanded, "collapsed() flips the default");
257        assert_eq!(item.item_type, 42);
258        assert!(
259            item.has_children,
260            "chaining must not clobber structural fields"
261        );
262    }
263
264    #[test]
265    fn disabled_and_non_selectable_chain() {
266        let item = TreeItem::leaf(2, NO_PARENT, 0, "x", "y")
267            .disabled()
268            .non_selectable();
269        assert!(!item.enabled);
270        assert!(!item.selectable);
271    }
272
273    #[test]
274    fn index_of_id_finds_first_match() {
275        let items = [
276            TreeItem::leaf(1, NO_PARENT, 0, "a", ""),
277            TreeItem::leaf(2, NO_PARENT, 0, "b", ""),
278            TreeItem::leaf(2, NO_PARENT, 0, "dup-of-b", ""),
279        ];
280        assert_eq!(index_of_id(&items, 1), Some(0));
281        assert_eq!(index_of_id(&items, 2), Some(1), "first match wins");
282        assert_eq!(index_of_id(&items, 99), None);
283    }
284
285    #[test]
286    fn index_of_id_on_empty() {
287        let items: [TreeItem; 0] = [];
288        assert_eq!(index_of_id(&items, 1), None);
289    }
290
291    #[test]
292    fn no_parent_is_minus_one() {
293        // Pinned: the sentinel is part of the public contract — hosts
294        // compare `parent_internal_id == NO_PARENT` to detect roots.
295        assert_eq!(NO_PARENT, -1);
296    }
297}