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