gpui_component/
tree.rs

1use std::{cell::RefCell, ops::Range, rc::Rc};
2
3use gpui::{
4    App, Context, ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement, KeyBinding,
5    ListSizingBehavior, MouseButton, ParentElement, Render, RenderOnce, SharedString,
6    StyleRefinement, Styled, UniformListScrollHandle, Window, div, prelude::FluentBuilder as _,
7    uniform_list,
8};
9
10use crate::{
11    StyledExt,
12    actions::{Confirm, SelectDown, SelectLeft, SelectRight, SelectUp},
13    list::ListItem,
14    scroll::Scrollbar,
15};
16
17const CONTEXT: &str = "Tree";
18pub(crate) fn init(cx: &mut App) {
19    cx.bind_keys([
20        KeyBinding::new("up", SelectUp, Some(CONTEXT)),
21        KeyBinding::new("down", SelectDown, Some(CONTEXT)),
22        KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
23        KeyBinding::new("right", SelectRight, Some(CONTEXT)),
24    ]);
25}
26
27/// Create a [`Tree`].
28///
29/// # Arguments
30///
31/// * `state` - The shared state managing the tree items.
32/// * `render_item` - A closure to render each tree item.
33///
34/// ```ignore
35/// let state = cx.new(|_| {
36///     TreeState::new().items(vec![
37///         TreeItem::new("src")
38///             .child(TreeItem::new("lib.rs"),
39///         TreeItem::new("Cargo.toml"),
40///         TreeItem::new("README.md"),
41///     ])
42/// });
43///
44/// tree(&state, |ix, entry, selected, window, cx| {
45///     let item = entry.item();
46///     ListItem::new(ix).pl(px(16.) * entry.depth()).child(item.label.clone())
47/// })
48/// ```
49pub fn tree<R>(state: &Entity<TreeState>, render_item: R) -> Tree
50where
51    R: Fn(usize, &TreeEntry, bool, &mut Window, &mut App) -> ListItem + 'static,
52{
53    Tree::new(state, render_item)
54}
55
56struct TreeItemState {
57    expanded: bool,
58    disabled: bool,
59}
60
61/// A tree item with a label, children, and an expanded state.
62#[derive(Clone)]
63pub struct TreeItem {
64    pub id: SharedString,
65    pub label: SharedString,
66    pub children: Vec<TreeItem>,
67    state: Rc<RefCell<TreeItemState>>,
68}
69
70/// A flat representation of a tree item with its depth.
71#[derive(Clone)]
72pub struct TreeEntry {
73    item: TreeItem,
74    depth: usize,
75}
76
77impl TreeEntry {
78    /// Get the source tree item.
79    #[inline]
80    pub fn item(&self) -> &TreeItem {
81        &self.item
82    }
83
84    /// The depth of this item in the tree.
85    #[inline]
86    pub fn depth(&self) -> usize {
87        self.depth
88    }
89
90    #[inline]
91    fn is_root(&self) -> bool {
92        self.depth == 0
93    }
94
95    /// Whether this item is a folder (has children).
96    #[inline]
97    pub fn is_folder(&self) -> bool {
98        self.item.is_folder()
99    }
100
101    /// Return true if the item is expanded.
102    #[inline]
103    pub fn is_expanded(&self) -> bool {
104        self.item.is_expanded()
105    }
106
107    #[inline]
108    pub fn is_disabled(&self) -> bool {
109        self.item.is_disabled()
110    }
111}
112
113impl TreeItem {
114    /// Create a new tree item with the given label.
115    ///
116    /// - The `id` for you to uniquely identify this item, then later you can use it for selection or other purposes.
117    /// - The `label` is the text to display for this item.
118    ///
119    /// For example, the `id` is the full file path, and the `label` is the file name.
120    ///
121    /// ```ignore
122    /// TreeItem::new("src/ui/button.rs", "button.rs")
123    /// ```
124    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
125        Self {
126            id: id.into(),
127            label: label.into(),
128            children: Vec::new(),
129            state: Rc::new(RefCell::new(TreeItemState {
130                expanded: false,
131                disabled: false,
132            })),
133        }
134    }
135
136    /// Add a child item to this tree item.
137    pub fn child(mut self, child: TreeItem) -> Self {
138        self.children.push(child);
139        self
140    }
141
142    /// Add multiple child items to this tree item.
143    pub fn children(mut self, children: impl IntoIterator<Item = TreeItem>) -> Self {
144        self.children.extend(children);
145        self
146    }
147
148    /// Set expanded state for this tree item.
149    pub fn expanded(self, expanded: bool) -> Self {
150        self.state.borrow_mut().expanded = expanded;
151        self
152    }
153
154    /// Set disabled state for this tree item.
155    pub fn disabled(self, disabled: bool) -> Self {
156        self.state.borrow_mut().disabled = disabled;
157        self
158    }
159
160    /// Whether this item is a folder (has children).
161    #[inline]
162    pub fn is_folder(&self) -> bool {
163        self.children.len() > 0
164    }
165
166    /// Return true if the item is disabled.
167    pub fn is_disabled(&self) -> bool {
168        self.state.borrow().disabled
169    }
170
171    /// Return true if the item is expanded.
172    #[inline]
173    pub fn is_expanded(&self) -> bool {
174        self.state.borrow().expanded
175    }
176}
177
178/// State for managing tree items.
179pub struct TreeState {
180    focus_handle: FocusHandle,
181    entries: Vec<TreeEntry>,
182    scroll_handle: UniformListScrollHandle,
183    selected_ix: Option<usize>,
184    render_item: Rc<dyn Fn(usize, &TreeEntry, bool, &mut Window, &mut App) -> ListItem>,
185}
186
187impl TreeState {
188    /// Create a new empty tree state.
189    pub fn new(cx: &mut App) -> Self {
190        Self {
191            selected_ix: None,
192            focus_handle: cx.focus_handle(),
193            scroll_handle: UniformListScrollHandle::default(),
194            entries: Vec::new(),
195            render_item: Rc::new(|_, _, _, _, _| ListItem::new(0)),
196        }
197    }
198
199    /// Set the tree items.
200    pub fn items(mut self, items: impl Into<Vec<TreeItem>>) -> Self {
201        let items = items.into();
202        self.entries.clear();
203        for item in items.into_iter() {
204            self.add_entry(item, 0);
205        }
206        self
207    }
208
209    /// Set the tree items.
210    pub fn set_items(&mut self, items: impl Into<Vec<TreeItem>>, cx: &mut Context<Self>) {
211        let items = items.into();
212        self.entries.clear();
213        for item in items.into_iter() {
214            self.add_entry(item, 0);
215        }
216        self.selected_ix = None;
217        cx.notify();
218    }
219
220    /// Get the currently selected index, if any.
221    pub fn selected_index(&self) -> Option<usize> {
222        self.selected_ix
223    }
224
225    /// Set the selected index, or `None` to clear selection.
226    pub fn set_selected_index(&mut self, ix: Option<usize>, cx: &mut Context<Self>) {
227        self.selected_ix = ix;
228        cx.notify();
229    }
230
231    pub fn scroll_to_item(&mut self, ix: usize, strategy: gpui::ScrollStrategy) {
232        self.scroll_handle.scroll_to_item(ix, strategy);
233    }
234
235    /// Get the currently selected entry, if any.
236    pub fn selected_entry(&self) -> Option<&TreeEntry> {
237        self.selected_ix.and_then(|ix| self.entries.get(ix))
238    }
239
240    fn add_entry(&mut self, item: TreeItem, depth: usize) {
241        self.entries.push(TreeEntry {
242            item: item.clone(),
243            depth,
244        });
245        if item.is_expanded() {
246            for child in &item.children {
247                self.add_entry(child.clone(), depth + 1);
248            }
249        }
250    }
251
252    fn toggle_expand(&mut self, ix: usize) {
253        let Some(entry) = self.entries.get_mut(ix) else {
254            return;
255        };
256        if !entry.is_folder() {
257            return;
258        }
259
260        entry.item.state.borrow_mut().expanded = !entry.is_expanded();
261        self.rebuild_entries();
262    }
263
264    fn rebuild_entries(&mut self) {
265        let root_items: Vec<TreeItem> = self
266            .entries
267            .iter()
268            .filter(|e| e.is_root())
269            .map(|e| e.item.clone())
270            .collect();
271        self.entries.clear();
272        for item in root_items.into_iter() {
273            self.add_entry(item, 0);
274        }
275    }
276
277    fn on_action_confirm(&mut self, _: &Confirm, _: &mut Window, cx: &mut Context<Self>) {
278        if let Some(selected_ix) = self.selected_ix {
279            if let Some(entry) = self.entries.get(selected_ix) {
280                if entry.is_folder() {
281                    self.toggle_expand(selected_ix);
282                    cx.notify();
283                }
284            }
285        }
286    }
287
288    fn on_action_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
289        if let Some(selected_ix) = self.selected_ix {
290            if let Some(entry) = self.entries.get(selected_ix) {
291                if entry.is_folder() && entry.is_expanded() {
292                    self.toggle_expand(selected_ix);
293                    cx.notify();
294                }
295            }
296        }
297    }
298
299    fn on_action_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
300        if let Some(selected_ix) = self.selected_ix {
301            if let Some(entry) = self.entries.get(selected_ix) {
302                if entry.is_folder() && !entry.is_expanded() {
303                    self.toggle_expand(selected_ix);
304                    cx.notify();
305                }
306            }
307        }
308    }
309
310    fn on_action_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
311        let mut selected_ix = self.selected_ix.unwrap_or(0);
312
313        if selected_ix > 0 {
314            selected_ix = selected_ix - 1;
315        } else {
316            selected_ix = self.entries.len().saturating_sub(1);
317        }
318
319        self.selected_ix = Some(selected_ix);
320        self.scroll_handle
321            .scroll_to_item(selected_ix, gpui::ScrollStrategy::Top);
322        cx.notify();
323    }
324
325    fn on_action_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
326        let mut selected_ix = self.selected_ix.unwrap_or(0);
327        if selected_ix + 1 < self.entries.len() {
328            selected_ix = selected_ix + 1;
329        } else {
330            selected_ix = 0;
331        }
332
333        self.selected_ix = Some(selected_ix);
334        self.scroll_handle
335            .scroll_to_item(selected_ix, gpui::ScrollStrategy::Bottom);
336        cx.notify();
337    }
338
339    fn on_entry_click(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Self>) {
340        self.selected_ix = Some(ix);
341        self.toggle_expand(ix);
342        cx.notify();
343    }
344}
345
346impl Render for TreeState {
347    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
348        let render_item = self.render_item.clone();
349
350        div()
351            .id("tree-state")
352            .size_full()
353            .relative()
354            .child(
355                uniform_list("entries", self.entries.len(), {
356                    cx.processor(move |state, visible_range: Range<usize>, window, cx| {
357                        let mut items = Vec::with_capacity(visible_range.len());
358                        for ix in visible_range {
359                            let entry = &state.entries[ix];
360                            let selected = Some(ix) == state.selected_ix;
361                            let item = (render_item)(ix, entry, selected, window, cx);
362
363                            let el = div()
364                                .id(ix)
365                                .child(item.disabled(entry.item().is_disabled()).selected(selected))
366                                .when(!entry.item().is_disabled(), |this| {
367                                    this.on_mouse_down(
368                                        MouseButton::Left,
369                                        cx.listener({
370                                            move |this, _, window, cx| {
371                                                this.on_entry_click(ix, window, cx);
372                                            }
373                                        }),
374                                    )
375                                });
376
377                            items.push(el)
378                        }
379
380                        items
381                    })
382                })
383                .flex_grow()
384                .size_full()
385                .track_scroll(self.scroll_handle.clone())
386                .with_sizing_behavior(ListSizingBehavior::Auto)
387                .into_any_element(),
388            )
389            .child(
390                div()
391                    .absolute()
392                    .top_0()
393                    .right_0()
394                    .bottom_0()
395                    .w(Scrollbar::width())
396                    .child(Scrollbar::vertical(&self.scroll_handle)),
397            )
398    }
399}
400
401/// A tree view element that displays hierarchical data.
402#[derive(IntoElement)]
403pub struct Tree {
404    id: ElementId,
405    state: Entity<TreeState>,
406    style: StyleRefinement,
407    render_item: Rc<dyn Fn(usize, &TreeEntry, bool, &mut Window, &mut App) -> ListItem>,
408}
409
410impl Tree {
411    pub fn new<R>(state: &Entity<TreeState>, render_item: R) -> Self
412    where
413        R: Fn(usize, &TreeEntry, bool, &mut Window, &mut App) -> ListItem + 'static,
414    {
415        Self {
416            id: ElementId::Name(format!("tree-{}", state.entity_id()).into()),
417            state: state.clone(),
418            style: StyleRefinement::default(),
419            render_item: Rc::new(move |ix, item, selected, window, app| {
420                render_item(ix, item, selected, window, app)
421            }),
422        }
423    }
424}
425
426impl Styled for Tree {
427    fn style(&mut self) -> &mut StyleRefinement {
428        &mut self.style
429    }
430}
431
432impl RenderOnce for Tree {
433    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
434        let focus_handle = self.state.read(cx).focus_handle.clone();
435
436        self.state
437            .update(cx, |state, _| state.render_item = self.render_item);
438
439        div()
440            .id(self.id)
441            .key_context(CONTEXT)
442            .track_focus(&focus_handle)
443            .on_action(window.listener_for(&self.state, TreeState::on_action_confirm))
444            .on_action(window.listener_for(&self.state, TreeState::on_action_left))
445            .on_action(window.listener_for(&self.state, TreeState::on_action_right))
446            .on_action(window.listener_for(&self.state, TreeState::on_action_up))
447            .on_action(window.listener_for(&self.state, TreeState::on_action_down))
448            .size_full()
449            .child(self.state)
450            .refine_style(&self.style)
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use indoc::indoc;
457
458    use super::TreeState;
459    use gpui::AppContext as _;
460
461    fn assert_entries(entries: &Vec<super::TreeEntry>, expected: &str) {
462        let actual: Vec<String> = entries
463            .iter()
464            .map(|e| {
465                let mut s = String::new();
466                s.push_str(&"    ".repeat(e.depth));
467                s.push_str(e.item().label.as_str());
468                s
469            })
470            .collect();
471        let actual = actual.join("\n");
472        assert_eq!(actual.trim(), expected.trim());
473    }
474
475    #[gpui::test]
476    fn test_tree_entry(cx: &mut gpui::TestAppContext) {
477        use super::TreeItem;
478
479        let items = vec![
480            TreeItem::new("src", "src")
481                .expanded(true)
482                .child(
483                    TreeItem::new("src/ui", "ui")
484                        .expanded(true)
485                        .child(TreeItem::new("src/ui/button.rs", "button.rs"))
486                        .child(TreeItem::new("src/ui/icon.rs", "icon.rs"))
487                        .child(TreeItem::new("src/ui/mod.rs", "mod.rs")),
488                )
489                .child(TreeItem::new("src/lib.rs", "lib.rs")),
490            TreeItem::new("Cargo.toml", "Cargo.toml"),
491            TreeItem::new("Cargo.lock", "Cargo.lock").disabled(true),
492            TreeItem::new("README.md", "README.md"),
493        ];
494
495        let state = cx.new(|cx| TreeState::new(cx).items(items));
496        state.update(cx, |state, _| {
497            assert_entries(
498                &state.entries,
499                indoc! {
500                    r#"
501                src
502                    ui
503                        button.rs
504                        icon.rs
505                        mod.rs
506                    lib.rs
507                Cargo.toml
508                Cargo.lock
509                README.md
510                "#
511                },
512            );
513
514            let entry = state.entries.get(0).unwrap();
515            assert_eq!(entry.depth(), 0);
516            assert_eq!(entry.is_root(), true);
517            assert_eq!(entry.is_folder(), true);
518            assert_eq!(entry.is_expanded(), true);
519
520            let entry = state.entries.get(1).unwrap();
521            assert_eq!(entry.depth(), 1);
522            assert_eq!(entry.is_root(), false);
523            assert_eq!(entry.is_folder(), true);
524            assert_eq!(entry.is_expanded(), true);
525            assert_eq!(entry.item().label.as_str(), "ui");
526
527            state.toggle_expand(1);
528            let entry = state.entries.get(1).unwrap();
529            assert_eq!(entry.is_expanded(), false);
530            assert_entries(
531                &state.entries,
532                indoc! {
533                    r#"
534                src
535                    ui
536                    lib.rs
537                Cargo.toml
538                Cargo.lock
539                README.md
540                "#
541                },
542            );
543        })
544    }
545}