1use std::{collections::HashMap, f32::consts::FRAC_PI_2, rc::Rc};
2
3use gpui::{
4 AnyElement, App, AppContext as _, Axis, ClickEvent, Context, CursorStyle, ElementId, Entity,
5 EventEmitter, FocusHandle, Hsla, InteractiveElement, IntoElement, KeyDownEvent, ParentElement,
6 Pixels, RenderOnce, ScrollStrategy, SharedString, StatefulInteractiveElement, StyleRefinement,
7 Styled, Subscription, UniformListScrollHandle, Window, canvas, div, prelude::FluentBuilder, px,
8 radians, transparent_black,
9};
10use gpui_base::{
11 StyledExt as _, TestSupportExt as _, Tree as BaseTree, TreeEntry, TreeEvent as BaseTreeEvent,
12 TreeItem as BaseTreeItem, TreeState as BaseTreeState,
13 actions::{Confirm, SelectDown, SelectLeft, SelectRight, SelectUp},
14};
15use gpui_material_components::{
16 DisplayScrollbar, DisplayScrollbarFade, DisplayScrollbarStyle, Icon, IconName, Text,
17};
18use gpui_material_foundation::{
19 FocusRingPlacement, InteractionFeedback, color,
20 control_feedback::{activate_feedback, feedback_target, ripple_state},
21 current_material_strings, current_material_theme,
22};
23use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Density, Direction, TypeRole};
24
25const DEFAULT_ROW_HEIGHT: f32 = 40.0;
26const MIN_ROW_HEIGHT: f32 = 32.0;
27const DEFAULT_INDENT: f32 = 20.0;
28const DEFAULT_MAX_HEIGHT: f32 = 360.0;
29const CHEVRON_SLOT_SIZE: f32 = 20.0;
30const CONTAINER_PADDING_Y: f32 = 4.0;
31
32type SelectHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
33type ActivateHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
34type ToggleHandler = Rc<dyn Fn(&SharedString, bool, &mut Window, &mut App)>;
35type CustomRowRenderer = Rc<dyn Fn(&TreeRowInfo, &mut Window, &mut App) -> AnyElement>;
36
37#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct TreeNode {
40 id: SharedString,
41 label: SharedString,
42 icon: Option<IconName>,
43 expanded: bool,
44 disabled: bool,
45 children: Vec<TreeNode>,
46}
47
48impl TreeNode {
49 pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
51 Self {
52 id: id.into(),
53 label: label.into(),
54 icon: None,
55 expanded: false,
56 disabled: false,
57 children: Vec::new(),
58 }
59 }
60
61 pub fn icon(mut self, icon: IconName) -> Self {
63 self.icon = Some(icon);
64 self
65 }
66
67 pub fn expanded(mut self, expanded: bool) -> Self {
69 self.expanded = expanded;
70 self
71 }
72
73 pub fn disabled(mut self, disabled: bool) -> Self {
75 self.disabled = disabled;
76 self
77 }
78
79 pub fn child(mut self, child: TreeNode) -> Self {
81 self.children.push(child);
82 self
83 }
84
85 pub fn children(mut self, children: impl IntoIterator<Item = TreeNode>) -> Self {
87 self.children.extend(children);
88 self
89 }
90
91 pub fn id(&self) -> &SharedString {
93 &self.id
94 }
95
96 pub fn label(&self) -> &SharedString {
98 &self.label
99 }
100
101 pub fn icon_name(&self) -> Option<IconName> {
103 self.icon
104 }
105
106 pub fn is_branch(&self) -> bool {
108 !self.children.is_empty()
109 }
110
111 pub fn is_expanded(&self) -> bool {
113 self.expanded
114 }
115
116 pub fn is_disabled(&self) -> bool {
118 self.disabled
119 }
120
121 pub fn child_nodes(&self) -> &[TreeNode] {
123 &self.children
124 }
125
126 fn to_base_item(&self) -> BaseTreeItem {
127 let mut item = BaseTreeItem::new(self.id.clone(), self.label.clone())
128 .expanded(self.expanded)
129 .disabled(self.disabled);
130 if !self.children.is_empty() {
131 item = item.children(self.children.iter().map(Self::to_base_item));
132 }
133 item
134 }
135
136 fn collect_icons(&self, out: &mut HashMap<SharedString, IconName>) {
137 if let Some(icon) = self.icon {
138 out.insert(self.id.clone(), icon);
139 }
140 for child in &self.children {
141 child.collect_icons(out);
142 }
143 }
144
145 fn set_expanded_by_id(&mut self, target_id: &str, expanded: bool) -> Option<bool> {
146 if self.id.as_ref() == target_id {
147 if self.children.is_empty() || self.disabled || self.expanded == expanded {
148 return Some(false);
149 }
150 self.expanded = expanded;
151 return Some(true);
152 }
153 for child in &mut self.children {
154 if let Some(changed) = child.set_expanded_by_id(target_id, expanded) {
155 return Some(changed);
156 }
157 }
158 None
159 }
160
161 fn is_expanded_by_id(&self, target_id: &str) -> Option<bool> {
162 if self.id.as_ref() == target_id {
163 return Some(self.expanded);
164 }
165 for child in &self.children {
166 if let Some(expanded) = child.is_expanded_by_id(target_id) {
167 return Some(expanded);
168 }
169 }
170 None
171 }
172
173 fn expand_ancestors(&mut self, target_id: &str, expanded_ids: &mut Vec<SharedString>) -> bool {
174 if self.id.as_ref() == target_id {
175 return true;
176 }
177 for child in &mut self.children {
178 if child.expand_ancestors(target_id, expanded_ids) {
179 if !self.expanded {
180 self.expanded = true;
181 expanded_ids.push(self.id.clone());
182 }
183 return true;
184 }
185 }
186 false
187 }
188
189 fn set_all_expanded(&mut self, expanded: bool) {
190 if !self.children.is_empty() && !self.disabled {
191 self.expanded = expanded;
192 }
193 for child in &mut self.children {
194 child.set_all_expanded(expanded);
195 }
196 }
197
198 fn find_enabled_by_id(&self, target_id: &str) -> Option<bool> {
199 if self.id.as_ref() == target_id {
200 return Some(!self.disabled);
201 }
202 for child in &self.children {
203 if let Some(enabled) = child.find_enabled_by_id(target_id) {
204 return Some(enabled);
205 }
206 }
207 None
208 }
209
210 fn flatten_visible(&self, depth: usize, out: &mut Vec<FlatNode>) {
211 out.push(FlatNode {
212 id: self.id.clone(),
213 depth,
214 is_branch: !self.children.is_empty(),
215 is_expanded: self.expanded,
216 is_disabled: self.disabled,
217 });
218 if self.expanded {
219 for child in &self.children {
220 child.flatten_visible(depth + 1, out);
221 }
222 }
223 }
224}
225
226#[derive(Clone, Debug, PartialEq, Eq)]
227struct FlatNode {
228 id: SharedString,
229 depth: usize,
230 is_branch: bool,
231 is_expanded: bool,
232 is_disabled: bool,
233}
234
235#[derive(Clone, Debug, PartialEq, Eq)]
237pub struct TreeRowInfo {
238 pub id: SharedString,
240 pub label: SharedString,
242 pub icon: Option<IconName>,
244 pub depth: usize,
246 pub is_branch: bool,
248 pub is_expanded: bool,
250 pub is_selected: bool,
252 pub is_disabled: bool,
254}
255
256#[derive(Clone, Debug, PartialEq, Eq)]
258pub enum TreeEvent {
259 Expanded(SharedString),
261 Collapsed(SharedString),
263 Selected(SharedString),
265 Activated(SharedString),
267}
268
269#[derive(Clone, Copy, Debug, Default, PartialEq)]
271pub struct TreeColors {
272 pub container: Option<Hsla>,
274 pub border: Option<Hsla>,
276 pub content: Option<Hsla>,
278 pub icon: Option<Hsla>,
280 pub selected_container: Option<Hsla>,
282 pub selected_content: Option<Hsla>,
284 pub disabled_content: Option<Hsla>,
286}
287
288struct ResolvedTreeColors {
289 container: Hsla,
290 border: Hsla,
291 content: Hsla,
292 icon: Hsla,
293 selected_container: Hsla,
294 selected_content: Hsla,
295 disabled_content: Hsla,
296 focus_ring: Hsla,
297}
298
299impl TreeColors {
300 fn resolve(self, scheme: &gpui_material_theme::ColorScheme) -> ResolvedTreeColors {
301 let tone = |role| color(scheme.color(role));
302 ResolvedTreeColors {
303 container: self
304 .container
305 .unwrap_or_else(|| tone(ColorRole::SurfaceContainerLow)),
306 border: self
307 .border
308 .unwrap_or_else(|| tone(ColorRole::OutlineVariant)),
309 content: self.content.unwrap_or_else(|| tone(ColorRole::OnSurface)),
310 icon: self
311 .icon
312 .unwrap_or_else(|| tone(ColorRole::OnSurfaceVariant)),
313 selected_container: self
314 .selected_container
315 .unwrap_or_else(|| tone(ColorRole::SecondaryContainer)),
316 selected_content: self
317 .selected_content
318 .unwrap_or_else(|| tone(ColorRole::OnSecondaryContainer)),
319 disabled_content: self
320 .disabled_content
321 .unwrap_or_else(|| tone(ColorRole::OnSurface).opacity(0.38)),
322 focus_ring: tone(ColorRole::Secondary),
323 }
324 }
325}
326
327pub struct TreeState {
333 base: Entity<BaseTreeState>,
334 container_focus: FocusHandle,
335 nodes: Vec<TreeNode>,
336 visible: Vec<FlatNode>,
337 icons: HashMap<SharedString, IconName>,
338 _base_subscription: Subscription,
339}
340
341impl EventEmitter<TreeEvent> for TreeState {}
342
343impl TreeState {
344 pub fn new(cx: &mut Context<Self>) -> Self {
346 let base = cx.new(|cx| BaseTreeState::new(cx));
347 let container_focus = cx.focus_handle();
348 let subscription = cx.subscribe(&base, |this, _, event: &BaseTreeEvent, cx| match event {
349 BaseTreeEvent::Expanded(id) => {
350 for node in &mut this.nodes {
351 if node.set_expanded_by_id(id.as_ref(), true).is_some() {
352 break;
353 }
354 }
355 this.rebuild_visible();
356 cx.emit(TreeEvent::Expanded(id.clone()));
357 cx.notify();
358 }
359 BaseTreeEvent::Collapsed(id) => {
360 for node in &mut this.nodes {
361 if node.set_expanded_by_id(id.as_ref(), false).is_some() {
362 break;
363 }
364 }
365 this.rebuild_visible();
366 cx.emit(TreeEvent::Collapsed(id.clone()));
367 cx.notify();
368 }
369 });
370 Self {
371 base,
372 container_focus,
373 nodes: Vec::new(),
374 visible: Vec::new(),
375 icons: HashMap::new(),
376 _base_subscription: subscription,
377 }
378 }
379
380 pub fn items(mut self, items: impl Into<Vec<TreeNode>>, cx: &mut Context<Self>) -> Self {
382 self.set_items(items, cx);
383 self
384 }
385
386 pub fn set_items(&mut self, items: impl Into<Vec<TreeNode>>, cx: &mut Context<Self>) {
388 self.nodes = items.into();
389 self.rebuild_icons();
390 self.rebuild_visible();
391 let base_items: Vec<BaseTreeItem> = self.nodes.iter().map(TreeNode::to_base_item).collect();
392 self.base.update(cx, |base, cx| {
393 base.set_items(base_items, cx);
394 });
395 cx.notify();
396 }
397
398 pub fn nodes(&self) -> &[TreeNode] {
400 &self.nodes
401 }
402
403 pub fn visible_count(&self) -> usize {
405 self.visible.len()
406 }
407
408 pub fn selected_index(&self, cx: &App) -> Option<usize> {
410 self.base.read(cx).selected_index()
411 }
412
413 pub fn selected_id(&self, cx: &App) -> Option<SharedString> {
415 self.base
416 .read(cx)
417 .selected_item()
418 .map(|item| item.id.clone())
419 }
420
421 pub fn is_expanded(&self, id: &str) -> bool {
423 self.nodes
424 .iter()
425 .find_map(|node| node.is_expanded_by_id(id))
426 .unwrap_or(false)
427 }
428
429 pub fn select(&mut self, id: Option<&str>, cx: &mut Context<Self>) {
433 let Some(target_id) = id else {
434 self.base
435 .update(cx, |base, cx| base.set_selected_index(None, cx));
436 cx.notify();
437 return;
438 };
439 let enabled = self
440 .nodes
441 .iter()
442 .find_map(|node| node.find_enabled_by_id(target_id))
443 .unwrap_or(false);
444 if !enabled {
445 return;
446 }
447 let mut expanded_ids = Vec::new();
448 for node in &mut self.nodes {
449 if node.expand_ancestors(target_id, &mut expanded_ids) {
450 break;
451 }
452 }
453 if !expanded_ids.is_empty() {
454 self.rebuild_visible();
455 self.sync_base_preserving_selection(Some(target_id), cx);
456 for expanded in expanded_ids.into_iter().rev() {
457 cx.emit(TreeEvent::Expanded(expanded));
458 }
459 } else {
460 let target_ix = self.visible.iter().position(|n| n.id.as_ref() == target_id);
461 self.base.update(cx, |base, cx| {
462 base.set_selected_index(target_ix, cx);
463 if let Some(ix) = target_ix {
464 base.scroll_to_item(ix, ScrollStrategy::Nearest);
465 }
466 });
467 }
468 cx.emit(TreeEvent::Selected(SharedString::from(
469 target_id.to_owned(),
470 )));
471 cx.notify();
472 }
473
474 pub fn set_expanded(&mut self, id: &str, expanded: bool, cx: &mut Context<Self>) -> bool {
476 let mut changed = false;
477 for node in &mut self.nodes {
478 if let Some(did_change) = node.set_expanded_by_id(id, expanded) {
479 changed = did_change;
480 break;
481 }
482 }
483 if !changed {
484 return false;
485 }
486 let prev_selected = self.selected_id(cx);
487 self.rebuild_visible();
488 self.sync_base_preserving_selection(prev_selected.as_deref(), cx);
489 let shared = SharedString::from(id.to_owned());
490 cx.emit(if expanded {
491 TreeEvent::Expanded(shared)
492 } else {
493 TreeEvent::Collapsed(shared)
494 });
495 cx.notify();
496 true
497 }
498
499 pub fn toggle_expanded(&mut self, id: &str, cx: &mut Context<Self>) -> Option<bool> {
502 let next = !self.is_expanded(id);
503 self.set_expanded(id, next, cx).then_some(next)
504 }
505
506 pub fn expand_all(&mut self, cx: &mut Context<Self>) {
508 let prev_selected = self.selected_id(cx);
509 for node in &mut self.nodes {
510 node.set_all_expanded(true);
511 }
512 self.rebuild_visible();
513 self.sync_base_preserving_selection(prev_selected.as_deref(), cx);
514 cx.notify();
515 }
516
517 pub fn collapse_all(&mut self, cx: &mut Context<Self>) {
519 let prev_selected = self.selected_id(cx);
520 for node in &mut self.nodes {
521 node.set_all_expanded(false);
522 }
523 self.rebuild_visible();
524 self.sync_base_preserving_selection(prev_selected.as_deref(), cx);
525 cx.notify();
526 }
527
528 pub fn reveal(&mut self, id: &str, strategy: ScrollStrategy, cx: &mut Context<Self>) {
530 let mut expanded_ids = Vec::new();
531 for node in &mut self.nodes {
532 if node.expand_ancestors(id, &mut expanded_ids) {
533 break;
534 }
535 }
536 if !expanded_ids.is_empty() {
537 let prev_selected = self.selected_id(cx);
538 self.rebuild_visible();
539 self.sync_base_preserving_selection(prev_selected.as_deref(), cx);
540 for expanded in expanded_ids.into_iter().rev() {
541 cx.emit(TreeEvent::Expanded(expanded));
542 }
543 }
544 if let Some(ix) = self.visible.iter().position(|n| n.id.as_ref() == id) {
545 self.base.update(cx, |base, _| {
546 base.scroll_to_item(ix, strategy);
547 });
548 }
549 cx.notify();
550 }
551
552 pub fn scroll_handle(&self, cx: &App) -> UniformListScrollHandle {
554 self.base.read(cx).scroll_handle().clone()
555 }
556
557 pub fn focus(&self, window: &mut Window, cx: &mut App) {
559 self.base.update(cx, |base, cx| {
560 base.focus(window, cx);
561 });
562 }
563
564 pub fn is_focused(&self, window: &Window, cx: &App) -> bool {
566 self.container_focus.contains_focused(window, cx)
567 }
568
569 fn rebuild_icons(&mut self) {
570 self.icons.clear();
571 for node in &self.nodes {
572 node.collect_icons(&mut self.icons);
573 }
574 }
575
576 fn rebuild_visible(&mut self) {
577 self.visible.clear();
578 for node in &self.nodes {
579 node.flatten_visible(0, &mut self.visible);
580 }
581 }
582
583 fn sync_base_preserving_selection(
584 &mut self,
585 selected_id: Option<&str>,
586 cx: &mut Context<Self>,
587 ) {
588 let base_items: Vec<BaseTreeItem> = self.nodes.iter().map(TreeNode::to_base_item).collect();
589 let selected_ix =
590 selected_id.and_then(|id| self.visible.iter().position(|n| n.id.as_ref() == id));
591 self.base.update(cx, |base, cx| {
592 base.set_items(base_items, cx);
593 base.set_selected_index(selected_ix, cx);
594 if let Some(ix) = selected_ix {
595 base.scroll_to_item(ix, ScrollStrategy::Nearest);
596 }
597 });
598 }
599
600 fn step_selection(&mut self, forward: bool, cx: &mut Context<Self>) -> Option<SharedString> {
601 let current = self.selected_index(cx);
602 let next_ix = next_enabled_index(&self.visible, current, forward)?;
603 let id = self.visible[next_ix].id.clone();
604 self.base.update(cx, |base, cx| {
605 base.set_selected_index(Some(next_ix), cx);
606 base.scroll_to_item(
607 next_ix,
608 if forward {
609 ScrollStrategy::Bottom
610 } else {
611 ScrollStrategy::Top
612 },
613 );
614 });
615 cx.emit(TreeEvent::Selected(id.clone()));
616 cx.notify();
617 Some(id)
618 }
619
620 fn jump_selection(&mut self, first: bool, cx: &mut Context<Self>) -> Option<SharedString> {
621 let next_ix = edge_enabled_index(&self.visible, first)?;
622 let id = self.visible[next_ix].id.clone();
623 self.base.update(cx, |base, cx| {
624 base.set_selected_index(Some(next_ix), cx);
625 base.scroll_to_item(
626 next_ix,
627 if first {
628 ScrollStrategy::Top
629 } else {
630 ScrollStrategy::Bottom
631 },
632 );
633 });
634 cx.emit(TreeEvent::Selected(id.clone()));
635 cx.notify();
636 Some(id)
637 }
638
639 fn handle_expand_key(
640 &mut self,
641 cx: &mut Context<Self>,
642 ) -> (Option<SharedString>, Option<(SharedString, bool)>) {
643 let Some(ix) = self.selected_index(cx) else {
644 return (self.jump_selection(true, cx), None);
645 };
646 let Some(node) = self.visible.get(ix).cloned() else {
647 return (None, None);
648 };
649 if node.is_disabled {
650 return (None, None);
651 }
652 if node.is_branch && !node.is_expanded {
653 if self.set_expanded(node.id.as_ref(), true, cx) {
654 return (None, Some((node.id, true)));
655 }
656 } else if node.is_branch && node.is_expanded {
657 if let Some(child_ix) = first_enabled_child_index(&self.visible, ix) {
659 let id = self.visible[child_ix].id.clone();
660 self.base.update(cx, |base, cx| {
661 base.set_selected_index(Some(child_ix), cx);
662 base.scroll_to_item(child_ix, ScrollStrategy::Nearest);
663 });
664 cx.emit(TreeEvent::Selected(id.clone()));
665 cx.notify();
666 return (Some(id), None);
667 }
668 }
669 (None, None)
670 }
671
672 fn handle_collapse_key(
673 &mut self,
674 cx: &mut Context<Self>,
675 ) -> (Option<SharedString>, Option<(SharedString, bool)>) {
676 let Some(ix) = self.selected_index(cx) else {
677 return (None, None);
678 };
679 let Some(node) = self.visible.get(ix).cloned() else {
680 return (None, None);
681 };
682 if node.is_disabled {
683 return (None, None);
684 }
685 if node.is_branch && node.is_expanded {
686 if self.set_expanded(node.id.as_ref(), false, cx) {
687 return (None, Some((node.id, false)));
688 }
689 } else if let Some(parent_ix) = nearest_enabled_ancestor_index(&self.visible, ix) {
690 let id = self.visible[parent_ix].id.clone();
691 self.base.update(cx, |base, cx| {
692 base.set_selected_index(Some(parent_ix), cx);
693 base.scroll_to_item(parent_ix, ScrollStrategy::Nearest);
694 });
695 cx.emit(TreeEvent::Selected(id.clone()));
696 cx.notify();
697 return (Some(id), None);
698 }
699 (None, None)
700 }
701
702 fn handle_row_click(
703 &mut self,
704 id: &SharedString,
705 window: &mut Window,
706 cx: &mut Context<Self>,
707 ) -> (bool, Option<bool>) {
708 let Some(ix) = self.visible.iter().position(|n| &n.id == id) else {
709 return (false, None);
710 };
711 let node = self.visible[ix].clone();
712 if node.is_disabled {
713 return (false, None);
714 }
715 let toggled = if node.is_branch {
716 let next_expanded = !node.is_expanded;
717 for root in &mut self.nodes {
718 if root
719 .set_expanded_by_id(id.as_ref(), next_expanded)
720 .is_some()
721 {
722 break;
723 }
724 }
725 self.rebuild_visible();
726 self.sync_base_preserving_selection(Some(id.as_ref()), cx);
727 cx.emit(if next_expanded {
728 TreeEvent::Expanded(id.clone())
729 } else {
730 TreeEvent::Collapsed(id.clone())
731 });
732 Some(next_expanded)
733 } else {
734 self.base.update(cx, |base, cx| {
735 base.set_selected_index(Some(ix), cx);
736 });
737 None
738 };
739 self.focus(window, cx);
740 cx.emit(TreeEvent::Selected(id.clone()));
741 cx.emit(TreeEvent::Activated(id.clone()));
742 cx.notify();
743 (true, toggled)
744 }
745
746 fn handle_activate_key(
747 &mut self,
748 cx: &mut Context<Self>,
749 ) -> (Option<SharedString>, Option<(SharedString, bool)>) {
750 let Some(ix) = self.selected_index(cx) else {
751 return (None, None);
752 };
753 let Some(node) = self.visible.get(ix).cloned() else {
754 return (None, None);
755 };
756 if node.is_disabled {
757 return (None, None);
758 }
759 let toggled = if node.is_branch {
760 self.toggle_expanded(node.id.as_ref(), cx)
761 .map(|expanded| (node.id.clone(), expanded))
762 } else {
763 None
764 };
765 cx.emit(TreeEvent::Activated(node.id.clone()));
766 (Some(node.id), toggled)
767 }
768}
769
770fn next_enabled_index(
771 visible: &[FlatNode],
772 current: Option<usize>,
773 forward: bool,
774) -> Option<usize> {
775 let len = visible.len();
776 if len == 0 {
777 return None;
778 }
779 let start = match current {
780 Some(ix) if ix < len => ix,
781 _ => return edge_enabled_index(visible, forward),
782 };
783 for offset in 1..=len {
784 let candidate = if forward {
785 (start + offset) % len
786 } else {
787 (start + len - offset) % len
788 };
789 if !visible[candidate].is_disabled {
790 return Some(candidate);
791 }
792 }
793 None
794}
795
796fn edge_enabled_index(visible: &[FlatNode], first: bool) -> Option<usize> {
797 if first {
798 visible.iter().position(|n| !n.is_disabled)
799 } else {
800 visible.iter().rposition(|n| !n.is_disabled)
801 }
802}
803
804fn first_enabled_child_index(visible: &[FlatNode], parent_ix: usize) -> Option<usize> {
805 let parent_depth = visible.get(parent_ix)?.depth;
806 for (ix, node) in visible.iter().enumerate().skip(parent_ix + 1) {
807 if node.depth <= parent_depth {
808 break;
809 }
810 if !node.is_disabled {
811 return Some(ix);
812 }
813 }
814 None
815}
816
817fn nearest_enabled_ancestor_index(visible: &[FlatNode], child_ix: usize) -> Option<usize> {
818 let mut target_depth = visible.get(child_ix)?.depth;
819 if target_depth == 0 {
820 return None;
821 }
822 for ix in (0..child_ix).rev() {
823 let node = &visible[ix];
824 if node.depth < target_depth {
825 if !node.is_disabled {
826 return Some(ix);
827 }
828 target_depth = node.depth;
829 if target_depth == 0 {
830 break;
831 }
832 }
833 }
834 None
835}
836
837pub(crate) fn tree_row_height(density: Density, override_height: Option<Pixels>) -> Pixels {
838 override_height
839 .unwrap_or_else(|| px(density.visual_size(DEFAULT_ROW_HEIGHT).max(MIN_ROW_HEIGHT)))
840}
841
842#[derive(IntoElement)]
844pub struct Tree {
845 id: ElementId,
846 state: Entity<TreeState>,
847 row_height: Option<Pixels>,
848 indent: Pixels,
849 shape: Option<CornerShape>,
850 colors: TreeColors,
851 show_scrollbar: bool,
852 scrollbar_style: DisplayScrollbarStyle,
853 scrollbar_fade: DisplayScrollbarFade,
854 accessible_label: Option<SharedString>,
855 render_row: Option<CustomRowRenderer>,
856 on_select: Option<SelectHandler>,
857 on_activate: Option<ActivateHandler>,
858 on_toggle: Option<ToggleHandler>,
859 style: StyleRefinement,
860}
861
862impl Tree {
863 pub fn new(id: impl Into<ElementId>, state: &Entity<TreeState>) -> Self {
865 Self {
866 id: id.into(),
867 state: state.clone(),
868 row_height: None,
869 indent: px(DEFAULT_INDENT),
870 shape: None,
871 colors: TreeColors::default(),
872 show_scrollbar: true,
873 scrollbar_style: DisplayScrollbarStyle::default(),
874 scrollbar_fade: DisplayScrollbarFade::default(),
875 accessible_label: None,
876 render_row: None,
877 on_select: None,
878 on_activate: None,
879 on_toggle: None,
880 style: StyleRefinement::default(),
881 }
882 }
883
884 pub fn row_height(mut self, height: Pixels) -> Self {
886 if f32::from(height).is_finite() && height > px(0.) {
887 self.row_height = Some(height);
888 }
889 self
890 }
891
892 pub fn indent(mut self, indent: Pixels) -> Self {
894 if f32::from(indent).is_finite() && indent >= px(0.) {
895 self.indent = indent;
896 }
897 self
898 }
899
900 pub fn shape(mut self, shape: CornerShape) -> Self {
902 self.shape = Some(shape);
903 self
904 }
905
906 pub fn colors(mut self, colors: TreeColors) -> Self {
908 self.colors = colors;
909 self
910 }
911
912 pub fn show_scrollbar(mut self, show: bool) -> Self {
914 self.show_scrollbar = show;
915 self
916 }
917
918 pub fn scrollbar_style(mut self, style: DisplayScrollbarStyle) -> Self {
920 self.scrollbar_style = style;
921 self
922 }
923
924 pub fn scrollbar_fade(mut self, fade: DisplayScrollbarFade) -> Self {
926 self.scrollbar_fade = fade;
927 self
928 }
929
930 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
932 self.accessible_label = Some(label.into());
933 self
934 }
935
936 pub fn render_row(
938 mut self,
939 renderer: impl Fn(&TreeRowInfo, &mut Window, &mut App) -> AnyElement + 'static,
940 ) -> Self {
941 self.render_row = Some(Rc::new(renderer));
942 self
943 }
944
945 pub fn on_select(
947 mut self,
948 handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
949 ) -> Self {
950 self.on_select = Some(Rc::new(handler));
951 self
952 }
953
954 pub fn on_activate(
956 mut self,
957 handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
958 ) -> Self {
959 self.on_activate = Some(Rc::new(handler));
960 self
961 }
962
963 pub fn on_toggle(
965 mut self,
966 handler: impl Fn(&SharedString, bool, &mut Window, &mut App) + 'static,
967 ) -> Self {
968 self.on_toggle = Some(Rc::new(handler));
969 self
970 }
971}
972
973impl Styled for Tree {
974 fn style(&mut self) -> &mut StyleRefinement {
975 &mut self.style
976 }
977}
978
979impl RenderOnce for Tree {
980 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
981 let theme = current_material_theme(window, cx).clone();
982 let strings = current_material_strings(window, cx).clone();
983 let direction = theme.layout.direction;
984 let rtl = direction == Direction::Rtl;
985 let density = theme.layout.density;
986 let reduced_motion = cx.reduce_motion();
987 let colors = self.colors.resolve(&theme.colors);
988 let row_height = tree_row_height(density, self.row_height);
989 let indent = self.indent;
990 let shape = self.shape.unwrap_or_else(|| CornerRole::Medium.shape());
991 let radii = shape.radii(100.0, 100.0, direction);
992
993 let (base_entity, container_focus, visible_count, scroll_handle, icons) = {
994 let state = self.state.read(cx);
995 (
996 state.base.clone(),
997 state.container_focus.clone(),
998 state.visible.len(),
999 state.base.read(cx).scroll_handle().clone(),
1000 Rc::new(state.icons.clone()),
1001 )
1002 };
1003 let tree_focused = container_focus.contains_focused(window, cx);
1004 let focus_visible = tree_focused && window.last_input_was_keyboard();
1005
1006 let on_select = self.on_select;
1007 let on_activate = self.on_activate;
1008 let on_toggle = self.on_toggle;
1009
1010 let row_state = self.state.clone();
1011 let row_select = on_select.clone();
1012 let row_activate = on_activate.clone();
1013 let row_toggle = on_toggle.clone();
1014 let custom_renderer = self.render_row;
1015 let tree_id = self.id.clone();
1016
1017 let act_up_state = self.state.clone();
1018 let act_up_select = on_select.clone();
1019 let act_down_state = self.state.clone();
1020 let act_down_select = on_select.clone();
1021 let act_left_state = self.state.clone();
1022 let act_left_select = on_select.clone();
1023 let act_left_toggle = on_toggle.clone();
1024 let act_right_state = self.state.clone();
1025 let act_right_select = on_select.clone();
1026 let act_right_toggle = on_toggle.clone();
1027 let act_confirm_state = self.state.clone();
1028 let act_confirm_activate = on_activate.clone();
1029 let act_confirm_toggle = on_toggle.clone();
1030
1031 let key_state = self.state.clone();
1032 let key_select = on_select;
1033 let key_activate = on_activate;
1034 let key_toggle = on_toggle;
1035
1036 let row_focus = container_focus.clone();
1037 let base_tree = BaseTree::new(&base_entity)
1038 .size_full()
1039 .list_style(StyleRefinement::default().size_full())
1040 .item(move |_ix, entry: &TreeEntry, entry_state, window, cx| {
1041 let item = entry.item();
1042 let id = item.id.clone();
1043 let label = item.label.clone();
1044 let depth = entry.depth();
1045 let is_branch = entry.is_folder();
1046 let is_expanded = entry.is_expanded();
1047 let is_disabled = entry.is_disabled();
1048 let is_selected = entry_state.is_selected();
1049 let icon_name = icons.get(&id).copied();
1050
1051 let row_elem_id = ElementId::from((tree_id.clone(), format!("node-{id}")));
1052 let feedback = ripple_state(&row_elem_id, !is_disabled, window, cx);
1053 let interaction = {
1054 let mut interaction =
1055 feedback
1056 .borrow()
1057 .interaction(!is_disabled, &row_focus, window);
1058 interaction.focus_visible = !is_disabled && is_selected && focus_visible;
1059 interaction
1060 };
1061
1062 let pill_bg = if is_selected {
1063 colors.selected_container
1064 } else {
1065 transparent_black()
1066 };
1067 let text_color = if is_disabled {
1068 colors.disabled_content
1069 } else if is_selected {
1070 colors.selected_content
1071 } else {
1072 colors.content
1073 };
1074 let icon_color = if is_disabled {
1075 colors.disabled_content
1076 } else if is_selected {
1077 colors.selected_content
1078 } else {
1079 colors.icon
1080 };
1081
1082 let start_indent = px(8.0) + indent * (depth as f32);
1083 let end_padding = px(12.0);
1084 let (pl, pr) = if rtl {
1085 (end_padding, start_indent)
1086 } else {
1087 (start_indent, end_padding)
1088 };
1089
1090 let chevron_el = if is_branch {
1091 let mut icon = Icon::new(IconName::ChevronRight)
1092 .size(px(18.))
1093 .color_override(icon_color);
1094 if is_expanded {
1095 icon = icon.rotate(radians(FRAC_PI_2));
1097 } else {
1098 icon = icon.mirror_in_rtl(true);
1099 }
1100 div()
1101 .w(px(CHEVRON_SLOT_SIZE))
1102 .h(px(CHEVRON_SLOT_SIZE))
1103 .flex_none()
1104 .flex()
1105 .items_center()
1106 .justify_center()
1107 .child(icon)
1108 .into_any_element()
1109 } else {
1110 div()
1111 .w(px(CHEVRON_SLOT_SIZE))
1112 .h(px(CHEVRON_SLOT_SIZE))
1113 .flex_none()
1114 .into_any_element()
1115 };
1116
1117 let body = if let Some(renderer) = &custom_renderer {
1118 let info = TreeRowInfo {
1119 id: id.clone(),
1120 label: label.clone(),
1121 icon: icon_name,
1122 depth,
1123 is_branch,
1124 is_expanded,
1125 is_selected,
1126 is_disabled,
1127 };
1128 renderer(&info, window, cx)
1129 } else {
1130 let leading_icon = icon_name.map(|name| {
1131 Icon::new(name)
1132 .size(px(18.))
1133 .color_override(icon_color)
1134 .mirror_in_rtl(false)
1135 });
1136 div()
1137 .flex_1()
1138 .min_w_0()
1139 .flex()
1140 .when(rtl, Styled::flex_row_reverse)
1141 .items_center()
1142 .gap_2()
1143 .children(leading_icon)
1144 .child(
1145 Text::new(label.clone())
1146 .role(TypeRole::BodyMedium)
1147 .emphasized(is_selected)
1148 .color_override(text_color)
1149 .max_lines(1),
1150 )
1151 .into_any_element()
1152 };
1153
1154 let pill_shape = CornerRole::Full.shape();
1155 let prepaint_feedback = feedback.clone();
1156 let paint_feedback = feedback.clone();
1157 let feedback_layer = canvas(
1158 move |bounds, window, _| {
1159 prepaint_feedback
1160 .borrow_mut()
1161 .set_rounded_shape(bounds, pill_shape, direction, window);
1162 },
1163 move |_, _, window, cx| {
1164 let state = paint_feedback.borrow();
1165 let Some(shape) = state.shape() else {
1166 return;
1167 };
1168 let now = cx.background_executor().now();
1169 InteractionFeedback::new(interaction, text_color, colors.focus_ring)
1170 .focus_ring_placement(FocusRingPlacement::Inset)
1171 .paint(shape, state.ripple(), now, reduced_motion, window);
1172 },
1173 )
1174 .absolute()
1175 .inset_0();
1176
1177 let pill = div()
1178 .id(row_elem_id)
1179 .relative()
1180 .size_full()
1181 .rounded_full()
1182 .bg(pill_bg)
1183 .text_color(text_color)
1184 .flex()
1185 .when(rtl, Styled::flex_row_reverse)
1186 .items_center()
1187 .gap_1()
1188 .pl(pl)
1189 .pr(pr)
1190 .overflow_hidden()
1191 .when(!is_disabled, |el| el.cursor(CursorStyle::PointingHand))
1192 .child(feedback_layer)
1193 .child(chevron_el)
1194 .child(body);
1195
1196 let pill = if !is_disabled {
1197 let click_feedback = feedback.clone();
1198 let click_state = row_state.clone();
1199 let click_id = id.clone();
1200 let on_select = row_select.clone();
1201 let on_activate = row_activate.clone();
1202 let on_toggle = row_toggle.clone();
1203 feedback_target(
1204 pill.on_click(move |event: &ClickEvent, window, cx| {
1205 if click_feedback.borrow().blocks_activation(event) {
1206 return;
1207 }
1208 activate_feedback(event, &click_feedback, window, cx);
1209 cx.stop_propagation();
1210 let (handled, toggled) = click_state.update(cx, |state, cx| {
1211 state.handle_row_click(&click_id, window, cx)
1212 });
1213 if handled {
1214 if let Some(handler) = &on_select {
1215 handler(&click_id, window, cx);
1216 }
1217 if let Some(handler) = &on_activate {
1218 handler(&click_id, window, cx);
1219 }
1220 if let (Some(expanded), Some(handler)) = (toggled, &on_toggle) {
1221 handler(&click_id, expanded, window, cx);
1222 }
1223 }
1224 }),
1225 feedback,
1226 true,
1227 None,
1228 )
1229 } else {
1230 pill
1231 };
1232
1233 div()
1234 .w_full()
1235 .h(row_height)
1236 .px_1p5()
1237 .py(px(1.))
1238 .child(pill)
1239 .into_any_element()
1240 });
1241
1242 let natural_height = px((visible_count.max(1) as f32 * f32::from(row_height)
1243 + CONTAINER_PADDING_Y * 2.0)
1244 .min(DEFAULT_MAX_HEIGHT));
1245 let default_label = self
1246 .accessible_label
1247 .unwrap_or_else(|| SharedString::from(strings.navigation.as_ref().to_owned()));
1248
1249 let mut container = div()
1250 .id(self.id.clone())
1251 .test_support()
1252 .aria_label(default_label)
1253 .track_focus(&container_focus)
1254 .tab_stop(false)
1255 .relative()
1256 .w_full()
1257 .h(natural_height)
1258 .py(px(CONTAINER_PADDING_Y))
1259 .bg(colors.container)
1260 .border_1()
1261 .border_color(colors.border)
1262 .rounded_tl(px(radii[0]))
1263 .rounded_tr(px(radii[1]))
1264 .rounded_br(px(radii[2]))
1265 .rounded_bl(px(radii[3]))
1266 .overflow_hidden()
1267 .capture_action(move |_: &SelectUp, window, cx| {
1268 cx.stop_propagation();
1269 let selected = act_up_state.update(cx, |state, cx| state.step_selection(false, cx));
1270 if let (Some(id), Some(handler)) = (selected, &act_up_select) {
1271 handler(&id, window, cx);
1272 }
1273 })
1274 .capture_action(move |_: &SelectDown, window, cx| {
1275 cx.stop_propagation();
1276 let selected =
1277 act_down_state.update(cx, |state, cx| state.step_selection(true, cx));
1278 if let (Some(id), Some(handler)) = (selected, &act_down_select) {
1279 handler(&id, window, cx);
1280 }
1281 })
1282 .capture_action(move |_: &SelectLeft, window, cx| {
1283 cx.stop_propagation();
1284 let (selected, toggled) = act_left_state.update(cx, |state, cx| {
1285 if rtl {
1286 state.handle_expand_key(cx)
1287 } else {
1288 state.handle_collapse_key(cx)
1289 }
1290 });
1291 if let (Some(id), Some(handler)) = (selected, &act_left_select) {
1292 handler(&id, window, cx);
1293 }
1294 if let (Some((id, expanded)), Some(handler)) = (toggled, &act_left_toggle) {
1295 handler(&id, expanded, window, cx);
1296 }
1297 })
1298 .capture_action(move |_: &SelectRight, window, cx| {
1299 cx.stop_propagation();
1300 let (selected, toggled) = act_right_state.update(cx, |state, cx| {
1301 if rtl {
1302 state.handle_collapse_key(cx)
1303 } else {
1304 state.handle_expand_key(cx)
1305 }
1306 });
1307 if let (Some(id), Some(handler)) = (selected, &act_right_select) {
1308 handler(&id, window, cx);
1309 }
1310 if let (Some((id, expanded)), Some(handler)) = (toggled, &act_right_toggle) {
1311 handler(&id, expanded, window, cx);
1312 }
1313 })
1314 .capture_action(move |_: &Confirm, window, cx| {
1315 cx.stop_propagation();
1316 let (activated, toggled) =
1317 act_confirm_state.update(cx, |state, cx| state.handle_activate_key(cx));
1318 if let (Some(id), Some(handler)) = (activated, &act_confirm_activate) {
1319 handler(&id, window, cx);
1320 }
1321 if let (Some((id, expanded)), Some(handler)) = (toggled, &act_confirm_toggle) {
1322 handler(&id, expanded, window, cx);
1323 }
1324 })
1325 .capture_key_down(move |event: &KeyDownEvent, window, cx| {
1326 if event.keystroke.modifiers.modified() {
1327 return;
1328 }
1329 match event.keystroke.key.as_str() {
1330 "home" => {
1331 cx.stop_propagation();
1332 let selected =
1333 key_state.update(cx, |state, cx| state.jump_selection(true, cx));
1334 if let (Some(id), Some(handler)) = (selected, &key_select) {
1335 handler(&id, window, cx);
1336 }
1337 }
1338 "end" => {
1339 cx.stop_propagation();
1340 let selected =
1341 key_state.update(cx, |state, cx| state.jump_selection(false, cx));
1342 if let (Some(id), Some(handler)) = (selected, &key_select) {
1343 handler(&id, window, cx);
1344 }
1345 }
1346 "space" => {
1347 cx.stop_propagation();
1348 let (activated, toggled) =
1349 key_state.update(cx, |state, cx| state.handle_activate_key(cx));
1350 if let (Some(id), Some(handler)) = (activated, &key_activate) {
1351 handler(&id, window, cx);
1352 }
1353 if let (Some((id, expanded)), Some(handler)) = (toggled, &key_toggle) {
1354 handler(&id, expanded, window, cx);
1355 }
1356 }
1357 _ => {}
1358 }
1359 })
1360 .child(base_tree);
1361
1362 if self.show_scrollbar {
1363 container = container.child(
1364 DisplayScrollbar::new((self.id, "scrollbar"), Axis::Vertical, &scroll_handle)
1365 .style(self.scrollbar_style)
1366 .fade(self.scrollbar_fade),
1367 );
1368 }
1369
1370 container.refine_style(&self.style)
1371 }
1372}
1373
1374#[cfg(test)]
1375mod tests {
1376 use super::*;
1377
1378 fn sample_flat() -> Vec<FlatNode> {
1379 vec![
1380 FlatNode {
1381 id: "root".into(),
1382 depth: 0,
1383 is_branch: true,
1384 is_expanded: true,
1385 is_disabled: false,
1386 },
1387 FlatNode {
1388 id: "disabled-child".into(),
1389 depth: 1,
1390 is_branch: false,
1391 is_expanded: false,
1392 is_disabled: true,
1393 },
1394 FlatNode {
1395 id: "child".into(),
1396 depth: 1,
1397 is_branch: false,
1398 is_expanded: false,
1399 is_disabled: false,
1400 },
1401 FlatNode {
1402 id: "sibling".into(),
1403 depth: 0,
1404 is_branch: false,
1405 is_expanded: false,
1406 is_disabled: false,
1407 },
1408 ]
1409 }
1410
1411 #[test]
1412 fn navigation_skips_disabled_nodes_and_resolves_parent_and_child() {
1413 let flat = sample_flat();
1414 assert_eq!(next_enabled_index(&flat, Some(0), true), Some(2));
1415 assert_eq!(next_enabled_index(&flat, Some(2), false), Some(0));
1416 assert_eq!(next_enabled_index(&flat, Some(3), true), Some(0));
1417 assert_eq!(first_enabled_child_index(&flat, 0), Some(2));
1418 assert_eq!(nearest_enabled_ancestor_index(&flat, 2), Some(0));
1419 assert_eq!(nearest_enabled_ancestor_index(&flat, 3), None);
1420 }
1421
1422 #[test]
1423 fn density_scales_tree_row_height() {
1424 let compact = tree_row_height(Density::Compact, None);
1425 let standard = tree_row_height(Density::Standard, None);
1426 let comfortable = tree_row_height(Density::Comfortable, None);
1427 assert!(compact < standard);
1428 assert!(standard < comfortable);
1429 assert_eq!(tree_row_height(Density::Compact, Some(px(48.))), px(48.));
1430 }
1431}