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::{
13    LayoutDirection,
14    actions::{Confirm, SelectDown, SelectLeft, SelectRight, SelectUp},
15    styled::StyledExt as _,
16};
17
18const CONTEXT: &str = "Tree";
19
20#[doc(hidden)]
21pub fn init(cx: &mut App) {
22    cx.bind_keys([
23        KeyBinding::new("up", SelectUp, Some(CONTEXT)),
24        KeyBinding::new("down", SelectDown, Some(CONTEXT)),
25        KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
26        KeyBinding::new("right", SelectRight, Some(CONTEXT)),
27    ]);
28}
29
30#[doc(hidden)]
31pub const fn key_context() -> &'static str {
32    CONTEXT
33}
34
35struct TreeItemState {
36    expanded: bool,
37    disabled: bool,
38}
39
40/// A tree item with a stable id, display label, children, and shared state.
41#[derive(Clone)]
42pub struct TreeItem {
43    pub id: SharedString,
44    pub label: SharedString,
45    pub children: Vec<TreeItem>,
46    state: Rc<RefCell<TreeItemState>>,
47}
48
49/// A flat representation of a tree item with its depth.
50#[derive(Clone)]
51pub struct TreeEntry {
52    item: TreeItem,
53    depth: usize,
54}
55
56impl TreeEntry {
57    pub fn new(item: TreeItem, depth: usize) -> Self {
58        Self { item, depth }
59    }
60
61    #[inline]
62    pub fn item(&self) -> &TreeItem {
63        &self.item
64    }
65
66    #[inline]
67    pub fn depth(&self) -> usize {
68        self.depth
69    }
70
71    #[inline]
72    pub fn is_root(&self) -> bool {
73        self.depth == 0
74    }
75
76    #[inline]
77    pub fn is_folder(&self) -> bool {
78        self.item.is_folder()
79    }
80
81    #[inline]
82    pub fn is_expanded(&self) -> bool {
83        self.item.is_expanded()
84    }
85
86    #[inline]
87    pub fn is_disabled(&self) -> bool {
88        self.item.is_disabled()
89    }
90}
91
92/// Event emitted by a tree when user-visible expansion state changes.
93#[derive(Clone, Debug, PartialEq, Eq)]
94pub enum TreeEvent {
95    Expanded(SharedString),
96    Collapsed(SharedString),
97}
98
99impl TreeItem {
100    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
101        Self {
102            id: id.into(),
103            label: label.into(),
104            children: Vec::new(),
105            state: Rc::new(RefCell::new(TreeItemState {
106                expanded: false,
107                disabled: false,
108            })),
109        }
110    }
111
112    pub fn child(mut self, child: TreeItem) -> Self {
113        self.children.push(child);
114        self
115    }
116
117    pub fn children(mut self, children: impl IntoIterator<Item = TreeItem>) -> Self {
118        self.children.extend(children);
119        self
120    }
121
122    pub fn expanded(self, expanded: bool) -> Self {
123        self.state.borrow_mut().expanded = expanded;
124        self
125    }
126
127    pub fn disabled(self, disabled: bool) -> Self {
128        self.state.borrow_mut().disabled = disabled;
129        self
130    }
131
132    #[inline]
133    pub fn is_folder(&self) -> bool {
134        !self.children.is_empty()
135    }
136
137    pub fn is_disabled(&self) -> bool {
138        self.state.borrow().disabled
139    }
140
141    #[inline]
142    pub fn is_expanded(&self) -> bool {
143        self.state.borrow().expanded
144    }
145
146    /// Returns the target's ancestors from nearest parent to root.
147    pub fn ancestors(&self, target_id: &SharedString) -> Option<Vec<TreeItem>> {
148        self.ancestor_refs(target_id)
149            .map(|path| path.into_iter().cloned().collect())
150    }
151
152    /// Like [`Self::ancestors`], but borrows the ancestors instead of
153    /// deep-cloning each one's subtree.
154    fn ancestor_refs(&self, target_id: &SharedString) -> Option<Vec<&TreeItem>> {
155        if self.id == *target_id {
156            return Some(Vec::new());
157        }
158
159        for child in &self.children {
160            if let Some(mut path) = child.ancestor_refs(target_id) {
161                path.push(self);
162                return Some(path);
163            }
164        }
165
166        None
167    }
168}
169
170/// The interaction state supplied while rendering a visible tree entry.
171#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
172pub struct TreeEntryState {
173    selected: bool,
174    right_clicked: bool,
175}
176
177impl TreeEntryState {
178    #[inline]
179    pub fn is_selected(self) -> bool {
180        self.selected
181    }
182
183    #[inline]
184    pub fn is_right_clicked(self) -> bool {
185        self.right_clicked
186    }
187}
188
189type RenderItem = dyn Fn(usize, &TreeEntry, TreeEntryState, &mut Window, &mut App) -> AnyElement;
190
191/// Behavior and interaction state for a virtualized tree.
192pub struct TreeState {
193    focus_handle: FocusHandle,
194    entries: Vec<TreeEntry>,
195    scroll_handle: UniformListScrollHandle,
196    selected_ix: Option<usize>,
197    right_clicked_ix: Option<usize>,
198    render_item: Rc<RenderItem>,
199    list_style: StyleRefinement,
200}
201
202impl EventEmitter<TreeEvent> for TreeState {}
203
204impl TreeState {
205    pub fn new(cx: &mut App) -> Self {
206        Self {
207            focus_handle: cx.focus_handle(),
208            entries: Vec::new(),
209            scroll_handle: UniformListScrollHandle::default(),
210            selected_ix: None,
211            right_clicked_ix: None,
212            render_item: Rc::new(|_, _, _, _, _| div().into_any_element()),
213            list_style: StyleRefinement::default(),
214        }
215    }
216
217    pub fn items(mut self, items: impl Into<Vec<TreeItem>>) -> Self {
218        self.replace_items(items.into());
219        self
220    }
221
222    pub fn set_items(&mut self, items: impl Into<Vec<TreeItem>>, cx: &mut Context<Self>) {
223        self.replace_items(items.into());
224        self.selected_ix = None;
225        self.right_clicked_ix = None;
226        cx.notify();
227    }
228
229    pub fn selected_index(&self) -> Option<usize> {
230        self.selected_ix
231    }
232
233    pub fn set_selected_index(&mut self, ix: Option<usize>, cx: &mut Context<Self>) {
234        self.selected_ix = ix;
235        cx.notify();
236    }
237
238    pub fn set_selected_item(&mut self, item: Option<&TreeItem>, cx: &mut Context<Self>) {
239        if let Some(item) = item {
240            self.selected_ix = self.index_of(&item.id);
241            if self.selected_ix.is_none() {
242                self.expand_ancestors(item.id.clone(), cx);
243                self.selected_ix = self.index_of(&item.id);
244            }
245        } else {
246            self.selected_ix = None;
247        }
248        cx.notify();
249    }
250
251    pub fn selected_item(&self) -> Option<&TreeItem> {
252        self.selected_ix
253            .and_then(|ix| self.entries.get(ix).map(TreeEntry::item))
254    }
255
256    pub fn selected_entry(&self) -> Option<&TreeEntry> {
257        self.selected_ix.and_then(|ix| self.entries.get(ix))
258    }
259
260    pub fn entry(&self, ix: usize) -> Option<&TreeEntry> {
261        self.entries.get(ix)
262    }
263
264    pub fn scroll_handle(&self) -> &UniformListScrollHandle {
265        &self.scroll_handle
266    }
267
268    pub fn scroll_to_item(&mut self, ix: usize, strategy: gpui::ScrollStrategy) {
269        self.scroll_handle.scroll_to_item(ix, strategy);
270    }
271
272    pub fn index_of(&self, id: &SharedString) -> Option<usize> {
273        self.entries.iter().position(|entry| &entry.item.id == id)
274    }
275
276    pub fn reveal_item(
277        &mut self,
278        id: &SharedString,
279        strategy: gpui::ScrollStrategy,
280        cx: &mut Context<Self>,
281    ) {
282        self.expand_ancestors(id.clone(), cx);
283        if let Some(ix) = self.index_of(id) {
284            self.scroll_to_item(ix, strategy);
285        }
286    }
287
288    pub fn focus(&mut self, window: &mut Window, cx: &mut App) {
289        self.focus_handle.focus(window, cx);
290    }
291
292    fn replace_items(&mut self, items: Vec<TreeItem>) {
293        self.entries.clear();
294        for item in items {
295            self.push_root(item);
296        }
297    }
298
299    fn expand_ancestors(&mut self, target_id: SharedString, cx: &mut Context<Self>) {
300        // Entries are in depth-first order, so the root containing the target
301        // precedes every descendant entry whose subtree could also contain it.
302        let ancestors = self
303            .entries
304            .iter()
305            .filter(|entry| entry.is_root())
306            .find_map(|entry| entry.item.ancestor_refs(&target_id))
307            .unwrap_or_default();
308
309        if ancestors.is_empty() {
310            return;
311        }
312
313        for ancestor in ancestors.into_iter().rev() {
314            if !ancestor.is_expanded() {
315                ancestor.state.borrow_mut().expanded = true;
316                cx.emit(TreeEvent::Expanded(ancestor.id.clone()));
317            }
318        }
319        self.rebuild_entries();
320    }
321
322    /// Moves an owned root item into the entries, flattening its visible
323    /// descendants by reference so the root's subtree is not cloned.
324    fn push_root(&mut self, mut item: TreeItem) {
325        let children = if item.is_expanded() {
326            std::mem::take(&mut item.children)
327        } else {
328            Vec::new()
329        };
330
331        let ix = self.entries.len();
332        self.entries.push(TreeEntry::new(item, 0));
333        if !children.is_empty() {
334            for child in &children {
335                self.add_entry(child, 1);
336            }
337            self.entries[ix].item.children = children;
338        }
339    }
340
341    fn add_entry(&mut self, item: &TreeItem, depth: usize) {
342        self.entries.push(TreeEntry::new(item.clone(), depth));
343        if item.is_expanded() {
344            for child in &item.children {
345                self.add_entry(child, depth + 1);
346            }
347        }
348    }
349
350    fn toggle_expand(&mut self, ix: usize, cx: &mut Context<Self>) {
351        let Some(entry) = self.entries.get(ix) else {
352            return;
353        };
354        if !entry.is_folder() {
355            return;
356        }
357
358        let expanded = !entry.is_expanded();
359        let id = entry.item.id.clone();
360        entry.item.state.borrow_mut().expanded = expanded;
361        cx.emit(if expanded {
362            TreeEvent::Expanded(id)
363        } else {
364            TreeEvent::Collapsed(id)
365        });
366        self.right_clicked_ix = None;
367        self.rebuild_entries();
368    }
369
370    fn rebuild_entries(&mut self) {
371        let roots = std::mem::take(&mut self.entries)
372            .into_iter()
373            .filter(TreeEntry::is_root)
374            .map(|entry| entry.item)
375            .collect::<Vec<_>>();
376        self.replace_items(roots);
377    }
378
379    fn on_action_confirm(&mut self, _: &Confirm, _: &mut Window, cx: &mut Context<Self>) {
380        if self
381            .selected_ix
382            .and_then(|ix| self.entries.get(ix).map(|entry| (ix, entry.is_folder())))
383            .is_some_and(|(ix, is_folder)| {
384                if is_folder {
385                    self.toggle_expand(ix, cx);
386                }
387                is_folder
388            })
389        {
390            cx.notify();
391        }
392    }
393
394    // The arrow toward the end edge expands and the one toward the start
395    // collapses: Right and Left in LTR, Left and Right in RTL.
396    fn on_action_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
397        let expand = LayoutDirection::global(cx).is_rtl();
398        self.set_selected_expanded(expand, cx);
399    }
400
401    fn on_action_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
402        let expand = !LayoutDirection::global(cx).is_rtl();
403        self.set_selected_expanded(expand, cx);
404    }
405
406    fn set_selected_expanded(&mut self, expanded: bool, cx: &mut Context<Self>) {
407        if let Some(ix) = self.selected_ix
408            && self
409                .entries
410                .get(ix)
411                .is_some_and(|entry| entry.is_folder() && entry.is_expanded() != expanded)
412        {
413            self.toggle_expand(ix, cx);
414            cx.notify();
415        }
416    }
417
418    fn on_action_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
419        let mut ix = self.selected_ix.unwrap_or(0);
420        ix = ix
421            .checked_sub(1)
422            .unwrap_or_else(|| self.entries.len().saturating_sub(1));
423        self.selected_ix = Some(ix);
424        self.scroll_handle
425            .scroll_to_item(ix, gpui::ScrollStrategy::Top);
426        cx.notify();
427    }
428
429    fn on_action_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
430        let mut ix = self.selected_ix.unwrap_or(0);
431        ix = if ix + 1 < self.entries.len() {
432            ix + 1
433        } else {
434            0
435        };
436        self.selected_ix = Some(ix);
437        self.scroll_handle
438            .scroll_to_item(ix, gpui::ScrollStrategy::Bottom);
439        cx.notify();
440    }
441
442    fn on_entry_click(&mut self, ix: usize, cx: &mut Context<Self>) {
443        self.selected_ix = Some(ix);
444        self.toggle_expand(ix, cx);
445        cx.notify();
446    }
447}
448
449impl Render for TreeState {
450    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
451        let render_item = self.render_item.clone();
452        uniform_list("entries", self.entries.len(), {
453            cx.processor(move |state, visible_range: Range<usize>, window, cx| {
454                visible_range
455                    .map(|ix| {
456                        let entry = &state.entries[ix];
457                        let entry_state = TreeEntryState {
458                            selected: Some(ix) == state.selected_ix,
459                            right_clicked: Some(ix) == state.right_clicked_ix,
460                        };
461                        div()
462                            .id(ix)
463                            .test_support()
464                            .role(gpui::Role::TreeItem)
465                            .aria_label(entry.item().label.clone())
466                            .aria_selected(entry_state.selected)
467                            .when(entry.is_folder(), |this| {
468                                this.aria_expanded(entry.is_expanded())
469                            })
470                            .child((render_item)(ix, entry, entry_state, window, cx))
471                            .when(!entry.is_disabled(), |this| {
472                                // Select and toggle on a full click, like `List` and `Table`
473                                // rows, so a press that is dragged away leaves the entry alone.
474                                this.on_click(cx.listener(move |state, _, _, cx| {
475                                    state.on_entry_click(ix, cx);
476                                }))
477                                .on_mouse_down(
478                                    MouseButton::Right,
479                                    cx.listener(move |state, _, _, cx| {
480                                        state.right_clicked_ix = Some(ix);
481                                        cx.notify();
482                                    }),
483                                )
484                            })
485                    })
486                    .collect()
487            })
488        })
489        .track_scroll(&self.scroll_handle)
490        .refine_style(&self.list_style)
491    }
492}
493
494/// An unstyled, virtualized tree element.
495///
496/// A click on an entry, a press and release on that same entry, selects it
497/// and expands or collapses it when it is a folder. Click handlers in the
498/// content from [`Tree::item`] run first, so they still see the previous
499/// selection. To drag entries, use `on_drag` on that content: a press that
500/// starts a drag is not a click.
501#[derive(IntoElement)]
502pub struct Tree {
503    id: ElementId,
504    state: Entity<TreeState>,
505    style: StyleRefinement,
506    list_style: StyleRefinement,
507    render_item: Rc<RenderItem>,
508}
509
510impl Tree {
511    pub fn new(state: &Entity<TreeState>) -> Self {
512        Self {
513            id: ElementId::Name(format!("tree-{}", state.entity_id()).into()),
514            state: state.clone(),
515            style: StyleRefinement::default(),
516            list_style: StyleRefinement::default(),
517            render_item: Rc::new(|_, _, _, _, _| div().into_any_element()),
518        }
519    }
520
521    /// Supplies the application-owned content for each visible entry.
522    pub fn item<R>(mut self, render_item: R) -> Self
523    where
524        R: Fn(usize, &TreeEntry, TreeEntryState, &mut Window, &mut App) -> AnyElement + 'static,
525    {
526        self.render_item = Rc::new(render_item);
527        self
528    }
529
530    /// Applies caller-owned presentation to the internal virtual list.
531    pub fn list_style(mut self, style: StyleRefinement) -> Self {
532        self.list_style = style;
533        self
534    }
535}
536
537impl Styled for Tree {
538    fn style(&mut self) -> &mut StyleRefinement {
539        &mut self.style
540    }
541}
542
543impl RenderOnce for Tree {
544    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
545        let focus_handle = self.state.read(cx).focus_handle.clone();
546        self.state.update(cx, |state, _| {
547            state.render_item = self.render_item;
548            state.list_style = self.list_style;
549        });
550
551        div()
552            .id(self.id)
553            .test_support()
554            .role(gpui::Role::Tree)
555            .key_context(CONTEXT)
556            .track_focus(&focus_handle)
557            .on_action(window.listener_for(&self.state, TreeState::on_action_confirm))
558            .on_action(window.listener_for(&self.state, TreeState::on_action_left))
559            .on_action(window.listener_for(&self.state, TreeState::on_action_right))
560            .on_action(window.listener_for(&self.state, TreeState::on_action_up))
561            .on_action(window.listener_for(&self.state, TreeState::on_action_down))
562            .child(self.state)
563            .refine_style(&self.style)
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570    use gpui::{
571        AppContext as _, Modifiers, MouseUpEvent, Pixels, Point, Subscription, TestAppContext,
572        VisualTestContext, point, px,
573    };
574
575    struct EventCollector {
576        events: Rc<RefCell<Vec<TreeEvent>>>,
577        _subscription: Subscription,
578    }
579
580    impl EventCollector {
581        fn new(state: &Entity<TreeState>, cx: &mut Context<Self>) -> Self {
582            let events = Rc::new(RefCell::new(Vec::new()));
583            let captured = events.clone();
584            let subscription = cx.subscribe(state, move |_, _, event, _| {
585                captured.borrow_mut().push(event.clone());
586            });
587            Self {
588                events,
589                _subscription: subscription,
590            }
591        }
592    }
593
594    impl Render for EventCollector {
595        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
596            div()
597        }
598    }
599
600    #[test]
601    fn clones_share_state_and_ancestors_keep_nearest_first_order() {
602        let leaf = TreeItem::new("leaf", "Leaf");
603        let branch = TreeItem::new("branch", "Branch").child(leaf.clone());
604        let root = TreeItem::new("root", "Root").child(branch);
605
606        leaf.clone().disabled(true).expanded(true);
607        assert!(leaf.is_disabled());
608        assert!(leaf.is_expanded());
609
610        let ancestors = root.ancestors(&"leaf".into()).unwrap();
611        assert_eq!(
612            ancestors
613                .iter()
614                .map(|item| item.id.as_str())
615                .collect::<Vec<_>>(),
616            vec!["branch", "root"]
617        );
618    }
619
620    #[gpui::test]
621    fn state_flattens_expanded_items_and_resets_selection(cx: &mut gpui::TestAppContext) {
622        let items = vec![
623            TreeItem::new("src", "src")
624                .expanded(true)
625                .child(TreeItem::new("src/lib.rs", "lib.rs")),
626            TreeItem::new("README.md", "README.md"),
627        ];
628        let state = cx.new(|cx| TreeState::new(cx).items(items));
629
630        state.update(cx, |state, cx| {
631            assert_eq!(state.entries.len(), 3);
632            assert_eq!(state.entries[1].depth(), 1);
633            state.set_selected_index(Some(1), cx);
634            state.set_items(vec![TreeItem::new("Cargo.toml", "Cargo.toml")], cx);
635            assert_eq!(state.selected_index(), None);
636            assert_eq!(state.entries.len(), 1);
637        });
638    }
639
640    #[gpui::test]
641    fn selecting_hidden_item_expands_its_ancestors(cx: &mut gpui::TestAppContext) {
642        let target = TreeItem::new("src/ui/tree.rs", "tree.rs");
643        let root =
644            TreeItem::new("src", "src").child(TreeItem::new("src/ui", "ui").child(target.clone()));
645        let state = cx.new(|cx| TreeState::new(cx).items(vec![root]));
646
647        state.update(cx, |state, cx| {
648            state.set_selected_item(Some(&target), cx);
649            assert_eq!(state.entries.len(), 3);
650            assert_eq!(
651                state.selected_item().map(|item| item.id.as_str()),
652                Some("src/ui/tree.rs")
653            );
654        });
655    }
656
657    #[gpui::test]
658    fn revealing_item_under_later_root_keeps_other_subtrees(cx: &mut gpui::TestAppContext) {
659        let guide = TreeItem::new("docs/guide", "guide").child(TreeItem::new("docs/guide/a", "a"));
660        let docs = TreeItem::new("docs", "docs").expanded(true).child(guide);
661        let ui = TreeItem::new("src/ui", "ui").child(TreeItem::new("src/ui/tree.rs", "tree.rs"));
662        let src = TreeItem::new("src", "src").child(ui);
663        let state = cx.new(|cx| TreeState::new(cx).items(vec![docs, src]));
664
665        state.update(cx, |state, cx| {
666            assert_eq!(state.entries.len(), 3);
667            state.reveal_item(&"src/ui/tree.rs".into(), gpui::ScrollStrategy::Top, cx);
668            assert_eq!(
669                state
670                    .entries
671                    .iter()
672                    .map(|entry| (entry.item().id.as_str(), entry.depth()))
673                    .collect::<Vec<_>>(),
674                vec![
675                    ("docs", 0),
676                    ("docs/guide", 1),
677                    ("src", 0),
678                    ("src/ui", 1),
679                    ("src/ui/tree.rs", 2),
680                ]
681            );
682            assert!(state.entries[0].is_folder());
683            assert_eq!(state.entries[0].item().children.len(), 1);
684
685            state.toggle_expand(1, cx);
686            assert_eq!(state.index_of(&"docs/guide/a".into()), Some(2));
687        });
688    }
689
690    #[gpui::test]
691    fn arrow_keys_expand_toward_the_end_edge(cx: &mut gpui::TestAppContext) {
692        let (state, cx) = cx.add_window_view(|_, cx| TreeState::new(cx));
693        for (direction, expand, collapse) in [
694            (LayoutDirection::Ltr, "right", "left"),
695            (LayoutDirection::Rtl, "left", "right"),
696        ] {
697            let press = |key: &str, cx: &mut VisualTestContext| {
698                cx.update(|window, cx| {
699                    state.update(cx, |s, cx| match key {
700                        "left" => s.on_action_left(&SelectLeft, window, cx),
701                        _ => s.on_action_right(&SelectRight, window, cx),
702                    })
703                });
704                state.read_with(cx, |s, _| s.entries.len() > 1)
705            };
706            cx.update(|_, cx| {
707                direction.set_global(cx);
708                state.update(cx, |s, cx| {
709                    s.set_items(
710                        vec![TreeItem::new("src", "src").child(TreeItem::new("lib.rs", "lib.rs"))],
711                        cx,
712                    );
713                    s.set_selected_index(Some(0), cx);
714                });
715            });
716            assert!(
717                !press(collapse, cx),
718                "{direction:?}: {collapse} keeps it collapsed"
719            );
720            assert!(press(expand, cx), "{direction:?}: {expand} expands");
721            assert!(
722                press(expand, cx),
723                "{direction:?}: {expand} keeps it expanded"
724            );
725            assert!(!press(collapse, cx), "{direction:?}: {collapse} collapses");
726        }
727    }
728
729    struct TreeHarness {
730        state: Entity<TreeState>,
731        draggable: bool,
732    }
733
734    struct DraggedEntry;
735
736    impl Render for DraggedEntry {
737        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
738            div()
739        }
740    }
741
742    impl Render for TreeHarness {
743        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
744            let draggable = self.draggable;
745            div().size_full().child(
746                Tree::new(&self.state)
747                    .size_full()
748                    .list_style(StyleRefinement::default().size_full())
749                    .item(move |ix, _, _, _, _| {
750                        div()
751                            .id(("tree-entry", ix))
752                            .debug_selector(move || format!("tree-entry-{ix}"))
753                            .h(px(20.))
754                            .w_full()
755                            .when(draggable, |this| {
756                                this.on_drag(ix, |_, _, _, cx| cx.new(|_| DraggedEntry))
757                            })
758                            .into_any_element()
759                    }),
760            )
761        }
762    }
763
764    /// Paints a tree of `items` in a test window and returns the center of
765    /// its first entry.
766    fn open_tree(
767        cx: &mut TestAppContext,
768        items: Vec<TreeItem>,
769        draggable: bool,
770    ) -> (Entity<TreeState>, &mut VisualTestContext, Point<Pixels>) {
771        let state = cx.new(|cx| TreeState::new(cx).items(items));
772        let (_, cx) = cx.add_window_view({
773            let state = state.clone();
774            move |_, _| TreeHarness { state, draggable }
775        });
776        cx.update(|window, cx| window.draw(cx).clear(cx));
777        let entry = cx
778            .debug_bounds("tree-entry-0")
779            .expect("the first entry is painted")
780            .center();
781        (state, cx, entry)
782    }
783
784    fn folder() -> TreeItem {
785        TreeItem::new("src", "src").child(TreeItem::new("src/lib.rs", "lib.rs"))
786    }
787
788    #[gpui::test]
789    fn entries_select_and_toggle_on_click_not_mouse_down(cx: &mut TestAppContext) {
790        let (state, cx, entry) = open_tree(cx, vec![folder()], false);
791
792        // A press alone (e.g. the start of a drag) must not select or expand.
793        cx.simulate_mouse_down(entry, MouseButton::Left, Modifiers::default());
794        state.read_with(cx, |state, _| {
795            assert_eq!(state.selected_index(), None);
796            assert_eq!(state.entries.len(), 1);
797        });
798        // Releasing away from the entry cancels the click.
799        cx.simulate_event(MouseUpEvent {
800            position: point(px(10.), px(500.)),
801            button: MouseButton::Left,
802            modifiers: Modifiers::default(),
803            click_count: 1,
804        });
805        cx.update(|window, cx| window.draw(cx).clear(cx));
806        state.read_with(cx, |state, _| assert_eq!(state.selected_index(), None));
807
808        cx.simulate_click(entry, Modifiers::default());
809        state.read_with(cx, |state, _| {
810            assert_eq!(state.selected_index(), Some(0));
811            assert_eq!(state.entries.len(), 2);
812        });
813    }
814
815    #[gpui::test]
816    fn dragging_an_entry_with_on_drag_does_not_select_or_toggle_it(cx: &mut TestAppContext) {
817        let (state, cx, entry) = open_tree(cx, vec![folder()], true);
818
819        // Start a drag, then drop it back on the entry it started from.
820        cx.simulate_mouse_down(entry, MouseButton::Left, Modifiers::default());
821        cx.simulate_mouse_move(
822            entry + point(px(8.), px(0.)),
823            MouseButton::Left,
824            Modifiers::default(),
825        );
826        cx.update(|window, cx| window.draw(cx).clear(cx));
827        cx.simulate_mouse_up(entry, MouseButton::Left, Modifiers::default());
828
829        state.read_with(cx, |state, _| {
830            assert_eq!(state.selected_index(), None);
831            assert_eq!(state.entries.len(), 1);
832        });
833    }
834
835    #[gpui::test]
836    fn right_click_neither_selects_nor_toggles(cx: &mut TestAppContext) {
837        let (state, cx, entry) = open_tree(cx, vec![folder()], false);
838
839        cx.simulate_mouse_down(entry, MouseButton::Right, Modifiers::default());
840        cx.simulate_mouse_up(entry, MouseButton::Right, Modifiers::default());
841
842        state.read_with(cx, |state, _| {
843            assert_eq!(state.right_clicked_ix, Some(0));
844            assert_eq!(state.selected_index(), None);
845            assert_eq!(state.entries.len(), 1);
846        });
847    }
848
849    #[gpui::test]
850    fn clicking_a_disabled_entry_does_nothing(cx: &mut TestAppContext) {
851        let (state, cx, entry) = open_tree(cx, vec![folder().disabled(true)], false);
852
853        cx.simulate_click(entry, Modifiers::default());
854
855        state.read_with(cx, |state, _| {
856            assert_eq!(state.selected_index(), None);
857            assert_eq!(state.entries.len(), 1);
858        });
859    }
860
861    #[gpui::test]
862    fn toggling_folder_rebuilds_visible_entries(cx: &mut gpui::TestAppContext) {
863        let root = TreeItem::new("src", "src").child(TreeItem::new("src/lib.rs", "lib.rs"));
864        let state = cx.new(|cx| TreeState::new(cx).items(vec![root]));
865
866        state.update(cx, |state, cx| {
867            state.toggle_expand(0, cx);
868            assert_eq!(state.entries.len(), 2);
869            state.toggle_expand(0, cx);
870            assert_eq!(state.entries.len(), 1);
871        });
872    }
873
874    #[gpui::test]
875    fn expansion_events_preserve_ids_and_set_items_stays_silent(cx: &mut gpui::TestAppContext) {
876        let root = TreeItem::new("src", "src").child(TreeItem::new("src/lib.rs", "lib.rs"));
877        let state = cx.new(|cx| TreeState::new(cx).items(vec![root]));
878        let collector = cx.new(|cx| EventCollector::new(&state, cx));
879
880        state.update(cx, |state, cx| {
881            state.toggle_expand(0, cx);
882            state.toggle_expand(0, cx);
883            state.set_items(vec![TreeItem::new("README.md", "README.md")], cx);
884        });
885
886        let events = collector.read_with(cx, |collector, _| collector.events.borrow().clone());
887        assert_eq!(
888            events,
889            vec![
890                TreeEvent::Expanded("src".into()),
891                TreeEvent::Collapsed("src".into()),
892            ]
893        );
894    }
895}