Skip to main content

gpui_base/
tree.rs

1use crate::TestSupportExt as _;
2use gpui::StatefulInteractiveElement as _;
3use std::{cell::RefCell, ops::Range, rc::Rc};
4
5use gpui::{
6    AnyElement, App, Context, ElementId, Entity, EventEmitter, FocusHandle, InteractiveElement,
7    IntoElement, KeyBinding, MouseButton, ParentElement, Render, RenderOnce, SharedString,
8    StyleRefinement, Styled, UniformListScrollHandle, Window, div, prelude::FluentBuilder as _,
9    uniform_list,
10};
11
12use crate::actions::{Confirm, SelectDown, SelectLeft, SelectRight, SelectUp};
13
14const CONTEXT: &str = "Tree";
15
16#[doc(hidden)]
17pub fn init(cx: &mut App) {
18    cx.bind_keys([
19        KeyBinding::new("up", SelectUp, Some(CONTEXT)),
20        KeyBinding::new("down", SelectDown, Some(CONTEXT)),
21        KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
22        KeyBinding::new("right", SelectRight, Some(CONTEXT)),
23    ]);
24}
25
26#[doc(hidden)]
27pub const fn key_context() -> &'static str {
28    CONTEXT
29}
30
31struct TreeItemState {
32    expanded: bool,
33    disabled: bool,
34}
35
36/// A tree item with a stable id, display label, children, and shared state.
37#[derive(Clone)]
38pub struct TreeItem {
39    pub id: SharedString,
40    pub label: SharedString,
41    pub children: Vec<TreeItem>,
42    state: Rc<RefCell<TreeItemState>>,
43}
44
45/// A flat representation of a tree item with its depth.
46#[derive(Clone)]
47pub struct TreeEntry {
48    item: TreeItem,
49    depth: usize,
50}
51
52impl TreeEntry {
53    pub fn new(item: TreeItem, depth: usize) -> Self {
54        Self { item, depth }
55    }
56
57    #[inline]
58    pub fn item(&self) -> &TreeItem {
59        &self.item
60    }
61
62    #[inline]
63    pub fn depth(&self) -> usize {
64        self.depth
65    }
66
67    #[inline]
68    pub fn is_root(&self) -> bool {
69        self.depth == 0
70    }
71
72    #[inline]
73    pub fn is_folder(&self) -> bool {
74        self.item.is_folder()
75    }
76
77    #[inline]
78    pub fn is_expanded(&self) -> bool {
79        self.item.is_expanded()
80    }
81
82    #[inline]
83    pub fn is_disabled(&self) -> bool {
84        self.item.is_disabled()
85    }
86}
87
88/// Event emitted by a tree when user-visible expansion state changes.
89#[derive(Clone, Debug, PartialEq, Eq)]
90pub enum TreeEvent {
91    Expanded(SharedString),
92    Collapsed(SharedString),
93}
94
95impl TreeItem {
96    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
97        Self {
98            id: id.into(),
99            label: label.into(),
100            children: Vec::new(),
101            state: Rc::new(RefCell::new(TreeItemState {
102                expanded: false,
103                disabled: false,
104            })),
105        }
106    }
107
108    pub fn child(mut self, child: TreeItem) -> Self {
109        self.children.push(child);
110        self
111    }
112
113    pub fn children(mut self, children: impl IntoIterator<Item = TreeItem>) -> Self {
114        self.children.extend(children);
115        self
116    }
117
118    pub fn expanded(self, expanded: bool) -> Self {
119        self.state.borrow_mut().expanded = expanded;
120        self
121    }
122
123    pub fn disabled(self, disabled: bool) -> Self {
124        self.state.borrow_mut().disabled = disabled;
125        self
126    }
127
128    #[inline]
129    pub fn is_folder(&self) -> bool {
130        !self.children.is_empty()
131    }
132
133    pub fn is_disabled(&self) -> bool {
134        self.state.borrow().disabled
135    }
136
137    #[inline]
138    pub fn is_expanded(&self) -> bool {
139        self.state.borrow().expanded
140    }
141
142    /// Returns the target's ancestors from nearest parent to root.
143    pub fn ancestors(&self, target_id: &SharedString) -> Option<Vec<TreeItem>> {
144        self.ancestor_refs(target_id)
145            .map(|path| path.into_iter().cloned().collect())
146    }
147
148    /// Like [`Self::ancestors`], but borrows the ancestors instead of
149    /// deep-cloning each one's subtree.
150    fn ancestor_refs(&self, target_id: &SharedString) -> Option<Vec<&TreeItem>> {
151        if self.id == *target_id {
152            return Some(Vec::new());
153        }
154
155        for child in &self.children {
156            if let Some(mut path) = child.ancestor_refs(target_id) {
157                path.push(self);
158                return Some(path);
159            }
160        }
161
162        None
163    }
164}
165
166/// The interaction state supplied while rendering a visible tree entry.
167#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
168pub struct TreeEntryState {
169    selected: bool,
170    right_clicked: bool,
171}
172
173impl TreeEntryState {
174    #[inline]
175    pub fn is_selected(self) -> bool {
176        self.selected
177    }
178
179    #[inline]
180    pub fn is_right_clicked(self) -> bool {
181        self.right_clicked
182    }
183}
184
185type RenderItem = dyn Fn(usize, &TreeEntry, TreeEntryState, &mut Window, &mut App) -> AnyElement;
186
187/// Behavior and interaction state for a virtualized tree.
188pub struct TreeState {
189    focus_handle: FocusHandle,
190    entries: Vec<TreeEntry>,
191    scroll_handle: UniformListScrollHandle,
192    selected_ix: Option<usize>,
193    right_clicked_ix: Option<usize>,
194    render_item: Rc<RenderItem>,
195    list_style: StyleRefinement,
196}
197
198impl EventEmitter<TreeEvent> for TreeState {}
199
200impl TreeState {
201    pub fn new(cx: &mut App) -> Self {
202        Self {
203            focus_handle: cx.focus_handle(),
204            entries: Vec::new(),
205            scroll_handle: UniformListScrollHandle::default(),
206            selected_ix: None,
207            right_clicked_ix: None,
208            render_item: Rc::new(|_, _, _, _, _| div().into_any_element()),
209            list_style: StyleRefinement::default(),
210        }
211    }
212
213    pub fn items(mut self, items: impl Into<Vec<TreeItem>>) -> Self {
214        self.replace_items(items.into());
215        self
216    }
217
218    pub fn set_items(&mut self, items: impl Into<Vec<TreeItem>>, cx: &mut Context<Self>) {
219        self.replace_items(items.into());
220        self.selected_ix = None;
221        self.right_clicked_ix = None;
222        cx.notify();
223    }
224
225    pub fn selected_index(&self) -> Option<usize> {
226        self.selected_ix
227    }
228
229    pub fn set_selected_index(&mut self, ix: Option<usize>, cx: &mut Context<Self>) {
230        self.selected_ix = ix;
231        cx.notify();
232    }
233
234    pub fn set_selected_item(&mut self, item: Option<&TreeItem>, cx: &mut Context<Self>) {
235        if let Some(item) = item {
236            self.selected_ix = self.index_of(&item.id);
237            if self.selected_ix.is_none() {
238                self.expand_ancestors(item.id.clone(), cx);
239                self.selected_ix = self.index_of(&item.id);
240            }
241        } else {
242            self.selected_ix = None;
243        }
244        cx.notify();
245    }
246
247    pub fn selected_item(&self) -> Option<&TreeItem> {
248        self.selected_ix
249            .and_then(|ix| self.entries.get(ix).map(TreeEntry::item))
250    }
251
252    pub fn selected_entry(&self) -> Option<&TreeEntry> {
253        self.selected_ix.and_then(|ix| self.entries.get(ix))
254    }
255
256    pub fn entry(&self, ix: usize) -> Option<&TreeEntry> {
257        self.entries.get(ix)
258    }
259
260    pub fn scroll_handle(&self) -> &UniformListScrollHandle {
261        &self.scroll_handle
262    }
263
264    pub fn scroll_to_item(&mut self, ix: usize, strategy: gpui::ScrollStrategy) {
265        self.scroll_handle.scroll_to_item(ix, strategy);
266    }
267
268    pub fn index_of(&self, id: &SharedString) -> Option<usize> {
269        self.entries.iter().position(|entry| &entry.item.id == id)
270    }
271
272    pub fn reveal_item(
273        &mut self,
274        id: &SharedString,
275        strategy: gpui::ScrollStrategy,
276        cx: &mut Context<Self>,
277    ) {
278        self.expand_ancestors(id.clone(), cx);
279        if let Some(ix) = self.index_of(id) {
280            self.scroll_to_item(ix, strategy);
281        }
282    }
283
284    pub fn focus(&mut self, window: &mut Window, cx: &mut App) {
285        self.focus_handle.focus(window, cx);
286    }
287
288    fn replace_items(&mut self, items: Vec<TreeItem>) {
289        self.entries.clear();
290        for item in items {
291            self.push_root(item);
292        }
293    }
294
295    fn expand_ancestors(&mut self, target_id: SharedString, cx: &mut Context<Self>) {
296        // Entries are in depth-first order, so the root containing the target
297        // precedes every descendant entry whose subtree could also contain it.
298        let ancestors = self
299            .entries
300            .iter()
301            .filter(|entry| entry.is_root())
302            .find_map(|entry| entry.item.ancestor_refs(&target_id))
303            .unwrap_or_default();
304
305        if ancestors.is_empty() {
306            return;
307        }
308
309        for ancestor in ancestors.into_iter().rev() {
310            if !ancestor.is_expanded() {
311                ancestor.state.borrow_mut().expanded = true;
312                cx.emit(TreeEvent::Expanded(ancestor.id.clone()));
313            }
314        }
315        self.rebuild_entries();
316    }
317
318    /// Moves an owned root item into the entries, flattening its visible
319    /// descendants by reference so the root's subtree is not cloned.
320    fn push_root(&mut self, mut item: TreeItem) {
321        let children = if item.is_expanded() {
322            std::mem::take(&mut item.children)
323        } else {
324            Vec::new()
325        };
326
327        let ix = self.entries.len();
328        self.entries.push(TreeEntry::new(item, 0));
329        if !children.is_empty() {
330            for child in &children {
331                self.add_entry(child, 1);
332            }
333            self.entries[ix].item.children = children;
334        }
335    }
336
337    fn add_entry(&mut self, item: &TreeItem, depth: usize) {
338        self.entries.push(TreeEntry::new(item.clone(), depth));
339        if item.is_expanded() {
340            for child in &item.children {
341                self.add_entry(child, depth + 1);
342            }
343        }
344    }
345
346    fn toggle_expand(&mut self, ix: usize, cx: &mut Context<Self>) {
347        let Some(entry) = self.entries.get(ix) else {
348            return;
349        };
350        if !entry.is_folder() {
351            return;
352        }
353
354        let expanded = !entry.is_expanded();
355        let id = entry.item.id.clone();
356        entry.item.state.borrow_mut().expanded = expanded;
357        cx.emit(if expanded {
358            TreeEvent::Expanded(id)
359        } else {
360            TreeEvent::Collapsed(id)
361        });
362        self.right_clicked_ix = None;
363        self.rebuild_entries();
364    }
365
366    fn rebuild_entries(&mut self) {
367        let roots = std::mem::take(&mut self.entries)
368            .into_iter()
369            .filter(TreeEntry::is_root)
370            .map(|entry| entry.item)
371            .collect::<Vec<_>>();
372        self.replace_items(roots);
373    }
374
375    fn on_action_confirm(&mut self, _: &Confirm, _: &mut Window, cx: &mut Context<Self>) {
376        if self
377            .selected_ix
378            .and_then(|ix| self.entries.get(ix).map(|entry| (ix, entry.is_folder())))
379            .is_some_and(|(ix, is_folder)| {
380                if is_folder {
381                    self.toggle_expand(ix, cx);
382                }
383                is_folder
384            })
385        {
386            cx.notify();
387        }
388    }
389
390    fn on_action_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
391        if let Some(ix) = self.selected_ix
392            && self
393                .entries
394                .get(ix)
395                .is_some_and(|entry| entry.is_folder() && entry.is_expanded())
396        {
397            self.toggle_expand(ix, cx);
398            cx.notify();
399        }
400    }
401
402    fn on_action_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
403        if let Some(ix) = self.selected_ix
404            && self
405                .entries
406                .get(ix)
407                .is_some_and(|entry| entry.is_folder() && !entry.is_expanded())
408        {
409            self.toggle_expand(ix, cx);
410            cx.notify();
411        }
412    }
413
414    fn on_action_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
415        let mut ix = self.selected_ix.unwrap_or(0);
416        ix = ix
417            .checked_sub(1)
418            .unwrap_or_else(|| self.entries.len().saturating_sub(1));
419        self.selected_ix = Some(ix);
420        self.scroll_handle
421            .scroll_to_item(ix, gpui::ScrollStrategy::Top);
422        cx.notify();
423    }
424
425    fn on_action_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
426        let mut ix = self.selected_ix.unwrap_or(0);
427        ix = if ix + 1 < self.entries.len() {
428            ix + 1
429        } else {
430            0
431        };
432        self.selected_ix = Some(ix);
433        self.scroll_handle
434            .scroll_to_item(ix, gpui::ScrollStrategy::Bottom);
435        cx.notify();
436    }
437
438    fn on_entry_click(&mut self, ix: usize, cx: &mut Context<Self>) {
439        self.selected_ix = Some(ix);
440        self.toggle_expand(ix, cx);
441        cx.notify();
442    }
443}
444
445impl Render for TreeState {
446    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
447        let render_item = self.render_item.clone();
448        uniform_list("entries", self.entries.len(), {
449            cx.processor(move |state, visible_range: Range<usize>, window, cx| {
450                visible_range
451                    .map(|ix| {
452                        let entry = &state.entries[ix];
453                        let entry_state = TreeEntryState {
454                            selected: Some(ix) == state.selected_ix,
455                            right_clicked: Some(ix) == state.right_clicked_ix,
456                        };
457                        div()
458                            .id(ix)
459                            .test_support()
460                            .role(gpui::Role::TreeItem)
461                            .aria_label(entry.item().label.clone())
462                            .aria_selected(entry_state.selected)
463                            .when(entry.is_folder(), |this| {
464                                this.aria_expanded(entry.is_expanded())
465                            })
466                            .child((render_item)(ix, entry, entry_state, window, cx))
467                            .when(!entry.is_disabled(), |this| {
468                                this.on_mouse_down(
469                                    MouseButton::Left,
470                                    cx.listener(move |state, _, _, cx| {
471                                        state.on_entry_click(ix, cx);
472                                    }),
473                                )
474                                .on_mouse_down(
475                                    MouseButton::Right,
476                                    cx.listener(move |state, _, _, cx| {
477                                        state.right_clicked_ix = Some(ix);
478                                        cx.notify();
479                                    }),
480                                )
481                            })
482                    })
483                    .collect()
484            })
485        })
486        .track_scroll(&self.scroll_handle)
487        .refine_style(&self.list_style)
488    }
489}
490
491/// An unstyled, virtualized tree element.
492#[derive(IntoElement)]
493pub struct Tree {
494    id: ElementId,
495    state: Entity<TreeState>,
496    style: StyleRefinement,
497    list_style: StyleRefinement,
498    render_item: Rc<RenderItem>,
499}
500
501impl Tree {
502    pub fn new(state: &Entity<TreeState>) -> Self {
503        Self {
504            id: ElementId::Name(format!("tree-{}", state.entity_id()).into()),
505            state: state.clone(),
506            style: StyleRefinement::default(),
507            list_style: StyleRefinement::default(),
508            render_item: Rc::new(|_, _, _, _, _| div().into_any_element()),
509        }
510    }
511
512    /// Supplies the application-owned content for each visible entry.
513    pub fn item<R>(mut self, render_item: R) -> Self
514    where
515        R: Fn(usize, &TreeEntry, TreeEntryState, &mut Window, &mut App) -> AnyElement + 'static,
516    {
517        self.render_item = Rc::new(render_item);
518        self
519    }
520
521    /// Applies caller-owned presentation to the internal virtual list.
522    pub fn list_style(mut self, style: StyleRefinement) -> Self {
523        self.list_style = style;
524        self
525    }
526}
527
528impl Styled for Tree {
529    fn style(&mut self) -> &mut StyleRefinement {
530        &mut self.style
531    }
532}
533
534impl RenderOnce for Tree {
535    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
536        let focus_handle = self.state.read(cx).focus_handle.clone();
537        self.state.update(cx, |state, _| {
538            state.render_item = self.render_item;
539            state.list_style = self.list_style;
540        });
541
542        div()
543            .id(self.id)
544            .test_support()
545            .role(gpui::Role::Tree)
546            .key_context(CONTEXT)
547            .track_focus(&focus_handle)
548            .on_action(window.listener_for(&self.state, TreeState::on_action_confirm))
549            .on_action(window.listener_for(&self.state, TreeState::on_action_left))
550            .on_action(window.listener_for(&self.state, TreeState::on_action_right))
551            .on_action(window.listener_for(&self.state, TreeState::on_action_up))
552            .on_action(window.listener_for(&self.state, TreeState::on_action_down))
553            .child(self.state)
554            .refine_style(&self.style)
555    }
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561    use gpui::{AppContext as _, Subscription};
562
563    struct EventCollector {
564        events: Rc<RefCell<Vec<TreeEvent>>>,
565        _subscription: Subscription,
566    }
567
568    impl EventCollector {
569        fn new(state: &Entity<TreeState>, cx: &mut Context<Self>) -> Self {
570            let events = Rc::new(RefCell::new(Vec::new()));
571            let captured = events.clone();
572            let subscription = cx.subscribe(state, move |_, _, event, _| {
573                captured.borrow_mut().push(event.clone());
574            });
575            Self {
576                events,
577                _subscription: subscription,
578            }
579        }
580    }
581
582    impl Render for EventCollector {
583        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
584            div()
585        }
586    }
587
588    #[test]
589    fn clones_share_state_and_ancestors_keep_nearest_first_order() {
590        let leaf = TreeItem::new("leaf", "Leaf");
591        let branch = TreeItem::new("branch", "Branch").child(leaf.clone());
592        let root = TreeItem::new("root", "Root").child(branch.clone());
593
594        leaf.clone().disabled(true).expanded(true);
595        assert!(leaf.is_disabled());
596        assert!(leaf.is_expanded());
597
598        let ancestors = root.ancestors(&"leaf".into()).unwrap();
599        assert_eq!(
600            ancestors
601                .iter()
602                .map(|item| item.id.as_str())
603                .collect::<Vec<_>>(),
604            vec!["branch", "root"]
605        );
606    }
607
608    #[gpui::test]
609    fn state_flattens_expanded_items_and_resets_selection(cx: &mut gpui::TestAppContext) {
610        let items = vec![
611            TreeItem::new("src", "src")
612                .expanded(true)
613                .child(TreeItem::new("src/lib.rs", "lib.rs")),
614            TreeItem::new("README.md", "README.md"),
615        ];
616        let state = cx.new(|cx| TreeState::new(cx).items(items));
617
618        state.update(cx, |state, cx| {
619            assert_eq!(state.entries.len(), 3);
620            assert_eq!(state.entries[1].depth(), 1);
621            state.set_selected_index(Some(1), cx);
622            state.set_items(vec![TreeItem::new("Cargo.toml", "Cargo.toml")], cx);
623            assert_eq!(state.selected_index(), None);
624            assert_eq!(state.entries.len(), 1);
625        });
626    }
627
628    #[gpui::test]
629    fn selecting_hidden_item_expands_its_ancestors(cx: &mut gpui::TestAppContext) {
630        let target = TreeItem::new("src/ui/tree.rs", "tree.rs");
631        let root =
632            TreeItem::new("src", "src").child(TreeItem::new("src/ui", "ui").child(target.clone()));
633        let state = cx.new(|cx| TreeState::new(cx).items(vec![root]));
634
635        state.update(cx, |state, cx| {
636            state.set_selected_item(Some(&target), cx);
637            assert_eq!(state.entries.len(), 3);
638            assert_eq!(
639                state.selected_item().map(|item| item.id.as_str()),
640                Some("src/ui/tree.rs")
641            );
642        });
643    }
644
645    #[gpui::test]
646    fn revealing_item_under_later_root_keeps_other_subtrees(cx: &mut gpui::TestAppContext) {
647        let guide = TreeItem::new("docs/guide", "guide").child(TreeItem::new("docs/guide/a", "a"));
648        let docs = TreeItem::new("docs", "docs").expanded(true).child(guide);
649        let ui = TreeItem::new("src/ui", "ui").child(TreeItem::new("src/ui/tree.rs", "tree.rs"));
650        let src = TreeItem::new("src", "src").child(ui);
651        let state = cx.new(|cx| TreeState::new(cx).items(vec![docs, src]));
652
653        state.update(cx, |state, cx| {
654            assert_eq!(state.entries.len(), 3);
655            state.reveal_item(&"src/ui/tree.rs".into(), gpui::ScrollStrategy::Top, cx);
656            assert_eq!(
657                state
658                    .entries
659                    .iter()
660                    .map(|entry| (entry.item().id.as_str(), entry.depth()))
661                    .collect::<Vec<_>>(),
662                vec![
663                    ("docs", 0),
664                    ("docs/guide", 1),
665                    ("src", 0),
666                    ("src/ui", 1),
667                    ("src/ui/tree.rs", 2),
668                ]
669            );
670            assert!(state.entries[0].is_folder());
671            assert_eq!(state.entries[0].item().children.len(), 1);
672
673            state.toggle_expand(1, cx);
674            assert_eq!(state.index_of(&"docs/guide/a".into()), Some(2));
675        });
676    }
677
678    #[gpui::test]
679    fn toggling_folder_rebuilds_visible_entries(cx: &mut gpui::TestAppContext) {
680        let root = TreeItem::new("src", "src").child(TreeItem::new("src/lib.rs", "lib.rs"));
681        let state = cx.new(|cx| TreeState::new(cx).items(vec![root]));
682
683        state.update(cx, |state, cx| {
684            state.toggle_expand(0, cx);
685            assert_eq!(state.entries.len(), 2);
686            state.toggle_expand(0, cx);
687            assert_eq!(state.entries.len(), 1);
688        });
689    }
690
691    #[gpui::test]
692    fn expansion_events_preserve_ids_and_set_items_stays_silent(cx: &mut gpui::TestAppContext) {
693        let root = TreeItem::new("src", "src").child(TreeItem::new("src/lib.rs", "lib.rs"));
694        let state = cx.new(|cx| TreeState::new(cx).items(vec![root]));
695        let collector = cx.new(|cx| EventCollector::new(&state, cx));
696
697        state.update(cx, |state, cx| {
698            state.toggle_expand(0, cx);
699            state.toggle_expand(0, cx);
700            state.set_items(vec![TreeItem::new("README.md", "README.md")], cx);
701        });
702
703        let events = collector.read_with(cx, |collector, _| collector.events.borrow().clone());
704        assert_eq!(
705            events,
706            vec![
707                TreeEvent::Expanded("src".into()),
708                TreeEvent::Collapsed("src".into()),
709            ]
710        );
711    }
712}