use std::{cell::RefCell, collections::HashSet, rc::Rc};
use arc_motion::{
CubicBezier, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Spacing, Typography, hex, oklab_mix};
use gpui_kit::{
App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, ParentElement,
PathBuilder, RenderOnce, Role, SharedString, Styled, Window, assets::IconName, canvas, div,
point, prelude::*, px, svg,
};
pub const TREE_ROW_PITCH_PX: f32 = 34.0;
pub const TREE_ROW_HEIGHT_PX: f32 = 32.0;
pub const TREE_INDENT_STEP_PX: f32 = 16.0;
pub const TREE_STAGGER_SECS: f64 = 0.035;
type ExpandedChangeCallback = Rc<dyn Fn(&Vec<SharedString>, &mut Window, &mut App)>;
type SelectCallback = Rc<dyn Fn(&TreeNode, &mut Window, &mut App)>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeNode {
pub id: SharedString,
pub label: SharedString,
pub children: Vec<TreeNode>,
pub icon: Option<IconName>,
}
impl TreeNode {
pub fn leaf(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
children: Vec::new(),
icon: None,
}
}
pub fn branch(
id: impl Into<SharedString>,
label: impl Into<SharedString>,
children: impl IntoIterator<Item = TreeNode>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
children: children.into_iter().collect(),
icon: None,
}
}
pub fn icon(mut self, icon: IconName) -> Self {
self.icon = Some(icon);
self
}
pub fn has_children(&self) -> bool {
!self.children.is_empty()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VisibleTreeNode {
pub node: TreeNode,
pub depth: usize,
pub parent_id: Option<SharedString>,
pub position: usize,
pub set_size: usize,
}
pub fn flatten_tree(nodes: &[TreeNode], expanded: &HashSet<SharedString>) -> Vec<VisibleTreeNode> {
fn walk(
nodes: &[TreeNode],
expanded: &HashSet<SharedString>,
depth: usize,
parent_id: Option<SharedString>,
out: &mut Vec<VisibleTreeNode>,
) {
let set_size = nodes.len();
for (idx, node) in nodes.iter().enumerate() {
out.push(VisibleTreeNode {
node: node.clone(),
depth,
parent_id: parent_id.clone(),
position: idx + 1,
set_size,
});
if !node.children.is_empty() && expanded.contains(&node.id) {
walk(
&node.children,
expanded,
depth + 1,
Some(node.id.clone()),
out,
);
}
}
}
let mut out = Vec::new();
walk(nodes, expanded, 1, None, &mut out);
out
}
pub fn tree_file_tone_color(label: &str, foreground: Hsla, muted: Hsla) -> Hsla {
let lower = label.to_ascii_lowercase();
if lower.ends_with(".tsx") || lower.ends_with(".ts") {
oklab_mix(hex(0x3178c6, 1.0), foreground, 0.78)
} else if lower.ends_with(".css") {
oklab_mix(hex(0x8b6ace, 1.0), foreground, 0.73)
} else if lower.ends_with(".md") {
oklab_mix(hex(0x38896b, 1.0), foreground, 0.74)
} else if lower.ends_with(".json") || lower.ends_with(".toml") {
oklab_mix(hex(0xc48637, 1.0), foreground, 0.78)
} else if lower.ends_with(".rs") {
oklab_mix(hex(0xd96b43, 1.0), foreground, 0.78)
} else {
muted
}
}
pub fn tree_row_reveal_sample(
elapsed_secs: f64,
stagger_order: usize,
reduced: bool,
) -> (f32, f32) {
if reduced {
return (1.0, 0.0);
}
let delay = stagger_order.min(7) as f64 * TREE_STAGGER_SECS;
let local = elapsed_secs - delay;
if local <= 0.0 {
return (0.0, -6.0);
}
if local >= 0.22 {
return (1.0, 0.0);
}
let t = (local / 0.22).clamp(0.0, 1.0) as f32;
let eased = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
(eased.clamp(0.0, 1.0), -6.0 * (1.0 - eased))
}
fn paint_rotating_chevron(cx: f32, cy: f32, angle_rad: f32, color: Hsla, window: &mut Window) {
let cos = angle_rad.cos();
let sin = angle_rad.sin();
let rot = |dx: f32, dy: f32| point(px(cx + dx * cos - dy * sin), px(cy + dx * sin + dy * cos));
let mut pb = PathBuilder::stroke(px(1.75));
pb.move_to(rot(-2.0, -4.0));
pb.line_to(rot(2.4, 0.0));
pb.line_to(rot(-2.0, 4.0));
if let Ok(path) = pb.build() {
window.paint_path(path, color);
}
}
#[derive(Clone)]
struct TreeViewInternal {
expanded: HashSet<SharedString>,
selected_id: Option<SharedString>,
focused_id: Option<SharedString>,
opened_id: Option<SharedString>,
opened_at: f64,
focus_handle: FocusHandle,
}
#[derive(IntoElement)]
pub struct TreeView {
id: ElementId,
nodes: Vec<TreeNode>,
default_expanded_ids: Vec<SharedString>,
expanded_ids: Option<Vec<SharedString>>,
selected_id: Option<SharedString>,
on_expanded_change: Option<ExpandedChangeCallback>,
on_select: Option<SelectCallback>,
}
impl TreeView {
pub fn new(id: impl Into<ElementId>, nodes: impl IntoIterator<Item = TreeNode>) -> Self {
Self {
id: id.into(),
nodes: nodes.into_iter().collect(),
default_expanded_ids: Vec::new(),
expanded_ids: None,
selected_id: None,
on_expanded_change: None,
on_select: None,
}
}
pub fn default_expanded_ids(
mut self,
ids: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.default_expanded_ids = ids.into_iter().map(Into::into).collect();
self
}
pub fn expanded_ids(mut self, ids: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
self.expanded_ids = Some(ids.into_iter().map(Into::into).collect());
self
}
pub fn selected_id(mut self, id: impl Into<SharedString>) -> Self {
self.selected_id = Some(id.into());
self
}
pub fn on_expanded_change(
mut self,
cb: impl Fn(&Vec<SharedString>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_expanded_change = Some(Rc::new(cb));
self
}
pub fn on_select(mut self, cb: impl Fn(&TreeNode, &mut Window, &mut App) + 'static) -> Self {
self.on_select = Some(Rc::new(cb));
self
}
}
impl RenderOnce for TreeView {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let default_exp: HashSet<SharedString> =
self.default_expanded_ids.iter().cloned().collect();
let first_id = self.nodes.first().map(|n| n.id.clone());
let state_cell = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), SharedString::from("tv-state")),
cx,
|_, cx| {
Rc::new(RefCell::new(TreeViewInternal {
expanded: default_exp,
selected_id: self.selected_id.clone(),
focused_id: first_id,
opened_id: None,
opened_at: now - 1.0,
focus_handle: cx.focus_handle(),
}))
},
)
.read(cx)
.clone();
let is_controlled_exp = self.expanded_ids.is_some();
let expanded: HashSet<SharedString> = if let Some(ref ext) = self.expanded_ids {
ext.iter().cloned().collect()
} else {
state_cell.borrow().expanded.clone()
};
let (selected_id, focused_id, opened_id, opened_elapsed, focus_handle) = {
let mut st = state_cell.borrow_mut();
if let Some(ref ext_sel) = self.selected_id {
st.selected_id = Some(ext_sel.clone());
}
let elapsed = (now - st.opened_at).max(0.0);
if st.opened_id.is_some() && elapsed >= 0.55 {
st.opened_id = None;
}
(
st.selected_id.clone(),
st.focused_id.clone(),
st.opened_id.clone(),
elapsed,
st.focus_handle.clone(),
)
};
if !reduced && opened_id.is_some() {
window.request_animation_frame();
}
let visible = flatten_tree(&self.nodes, &expanded);
let opened_index = opened_id
.as_ref()
.and_then(|oid| visible.iter().position(|v| &v.node.id == oid));
let selected_index = selected_id
.as_ref()
.and_then(|sid| visible.iter().position(|v| &v.node.id == sid));
let selection_pill = selected_index.map(|sel_idx| {
let target_y = sel_idx as f32 * TREE_ROW_PITCH_PX + 2.0;
let animated_y = if reduced {
target_y
} else {
arc_spring_with_options(
ElementId::NamedChild(
self.id.clone().into(),
SharedString::from("selection-y"),
),
target_y,
SpringOptions::new(motion.spring.morph).with_initial_value(target_y),
window,
cx,
)
.value
};
div()
.absolute()
.left_0()
.right_0()
.top(px(animated_y))
.h(px(TREE_ROW_HEIGHT_PX))
.rounded(px(10.0))
.bg(colors.surface_muted)
});
let mut rows_els = Vec::with_capacity(visible.len());
for (idx, item) in visible.iter().enumerate() {
let has_children = item.node.has_children();
let is_expanded = has_children && expanded.contains(&item.node.id);
let is_selected = selected_id.as_ref() == Some(&item.node.id);
let is_focused = focused_id.as_ref() == Some(&item.node.id);
let (row_opacity, row_x) = if let Some(oi) = opened_index {
if idx > oi && item.parent_id.as_ref() == opened_id.as_ref() {
tree_row_reveal_sample(opened_elapsed, idx - oi - 1, reduced)
} else {
(1.0, 0.0)
}
} else {
(1.0, 0.0)
};
let target_angle = if is_expanded {
std::f32::consts::FRAC_PI_2
} else {
0.0
};
let chevron_angle = if !has_children {
0.0
} else if reduced {
target_angle
} else {
arc_spring_with_options(
ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("chev-{}", item.node.id)),
),
target_angle,
SpringOptions::new(motion.spring.snappy).with_initial_value(target_angle),
window,
cx,
)
.value
};
let indent_left = 10.0 + (item.depth.saturating_sub(1) as f32) * TREE_INDENT_STEP_PX;
let row_fg = if is_selected {
colors.foreground
} else {
colors.text_secondary
};
let icon_color = if has_children {
if is_expanded || is_selected {
colors.foreground
} else {
colors.text_secondary
}
} else {
tree_file_tone_color(
item.node.label.as_ref(),
colors.foreground,
colors.text_muted,
)
};
let icon_name = item.node.icon.unwrap_or({
if has_children {
if is_expanded {
IconName::FolderOpen
} else {
IconName::Folder
}
} else {
IconName::File
}
});
let click_state = state_cell.clone();
let click_node = item.node.clone();
let click_on_exp = self.on_expanded_change.clone();
let click_on_sel = self.on_select.clone();
let click_ext_exp = self.expanded_ids.clone();
let chevron_color = colors.text_muted;
let mut row = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("row-{}", item.node.id)),
))
.role(Role::TreeItem)
.relative()
.left(px(row_x))
.opacity(row_opacity)
.w_full()
.h(px(TREE_ROW_HEIGHT_PX))
.mt(px(2.0))
.pl(px(indent_left))
.pr(px(10.0))
.rounded(px(10.0))
.cursor_pointer()
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.text_size(Typography::TEXT_SM)
.text_color(row_fg)
.hover(move |s| {
if is_selected {
s.text_color(colors.foreground)
} else {
s.bg(oklab_mix(colors.surface_muted, colors.surface, 0.72))
.text_color(colors.foreground)
}
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let t_now = motion_now(cx);
let next_exp_vec = {
let mut st = click_state.borrow_mut();
st.focused_id = Some(click_node.id.clone());
st.selected_id = Some(click_node.id.clone());
if click_node.has_children() {
let mut next_set: HashSet<SharedString> = click_ext_exp
.as_ref()
.map(|v| v.iter().cloned().collect())
.unwrap_or_else(|| st.expanded.clone());
if next_set.contains(&click_node.id) {
next_set.remove(&click_node.id);
} else {
next_set.insert(click_node.id.clone());
st.opened_id = Some(click_node.id.clone());
st.opened_at = t_now;
}
if !is_controlled_exp {
st.expanded = next_set.clone();
}
let mut v: Vec<SharedString> = next_set.into_iter().collect();
v.sort();
Some(v)
} else {
None
}
};
if let Some(ref cb) = click_on_sel {
cb(&click_node, window, cx);
}
if let (Some(v), Some(cb)) = (next_exp_vec, &click_on_exp) {
cb(&v, window, cx);
}
window.refresh();
});
for guide_depth in 2..=item.depth {
let guide_x = 16.5 + (guide_depth - 2) as f32 * TREE_INDENT_STEP_PX;
row = row.child(
div()
.absolute()
.top(px(4.0))
.bottom(px(4.0))
.left(px(guide_x))
.w(px(1.0))
.bg(colors.border),
);
}
if is_focused && !is_selected {
row = row.border_1().border_color(colors.border_strong);
}
row = row
.child(
div()
.w(px(14.0))
.h(px(16.0))
.flex_shrink_0()
.flex()
.items_center()
.justify_center()
.when(has_children, |el| {
el.child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let cx_p = f32::from(bounds.origin.x)
+ f32::from(bounds.size.width) * 0.5;
let cy_p = f32::from(bounds.origin.y)
+ f32::from(bounds.size.height) * 0.5;
paint_rotating_chevron(
cx_p,
cy_p,
chevron_angle,
chevron_color,
window,
);
},
)
.size_full(),
)
}),
)
.child(
svg()
.path(icon_name.path())
.size(px(16.0))
.flex_shrink_0()
.text_color(icon_color),
)
.child(
div()
.flex_1()
.min_w(px(0.0))
.truncate()
.child(item.node.label.clone()),
);
rows_els.push(row);
}
let key_state = state_cell.clone();
let key_visible = visible.clone();
let key_on_exp = self.on_expanded_change.clone();
let key_on_sel = self.on_select.clone();
let key_ext_exp = self.expanded_ids.clone();
div()
.id(self.id)
.role(Role::Tree)
.track_focus(&focus_handle)
.w_full()
.min_w(px(0.0))
.pt(px(6.0))
.pb(px(8.0))
.px(px(8.0))
.rounded(px(8.0))
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.text_color(colors.foreground)
.overflow_hidden()
.on_key_down(move |ev: &KeyDownEvent, window, cx| {
if key_visible.is_empty() {
return;
}
let key = ev.keystroke.key.as_str();
let t_now = motion_now(cx);
let cur_idx = {
let st = key_state.borrow();
st.focused_id
.as_ref()
.or(st.selected_id.as_ref())
.and_then(|id| key_visible.iter().position(|v| &v.node.id == id))
.unwrap_or(0)
};
let cur_item = &key_visible[cur_idx];
let mut sel_to_notify: Option<TreeNode> = None;
let mut exp_to_notify: Option<Vec<SharedString>> = None;
let mut handled = false;
match key {
"down" | "arrowdown" => {
let next_idx = (cur_idx + 1).min(key_visible.len() - 1);
key_state.borrow_mut().focused_id =
Some(key_visible[next_idx].node.id.clone());
handled = true;
}
"up" | "arrowup" => {
let prev_idx = cur_idx.saturating_sub(1);
key_state.borrow_mut().focused_id =
Some(key_visible[prev_idx].node.id.clone());
handled = true;
}
"home" => {
key_state.borrow_mut().focused_id = Some(key_visible[0].node.id.clone());
handled = true;
}
"end" => {
key_state.borrow_mut().focused_id =
Some(key_visible[key_visible.len() - 1].node.id.clone());
handled = true;
}
"right" | "arrowright" => {
if cur_item.node.has_children() {
let mut st = key_state.borrow_mut();
let mut next_set: HashSet<SharedString> = key_ext_exp
.as_ref()
.map(|v| v.iter().cloned().collect())
.unwrap_or_else(|| st.expanded.clone());
if !next_set.contains(&cur_item.node.id) {
next_set.insert(cur_item.node.id.clone());
st.opened_id = Some(cur_item.node.id.clone());
st.opened_at = t_now;
if !is_controlled_exp {
st.expanded = next_set.clone();
}
let mut v: Vec<SharedString> = next_set.into_iter().collect();
v.sort();
exp_to_notify = Some(v);
} else if let Some(child) = key_visible.get(cur_idx + 1)
&& child.parent_id.as_ref() == Some(&cur_item.node.id)
{
st.focused_id = Some(child.node.id.clone());
}
handled = true;
}
}
"left" | "arrowleft" => {
let mut st = key_state.borrow_mut();
let mut next_set: HashSet<SharedString> = key_ext_exp
.as_ref()
.map(|v| v.iter().cloned().collect())
.unwrap_or_else(|| st.expanded.clone());
if cur_item.node.has_children() && next_set.contains(&cur_item.node.id) {
next_set.remove(&cur_item.node.id);
if !is_controlled_exp {
st.expanded = next_set.clone();
}
let mut v: Vec<SharedString> = next_set.into_iter().collect();
v.sort();
exp_to_notify = Some(v);
handled = true;
} else if let Some(ref pid) = cur_item.parent_id {
st.focused_id = Some(pid.clone());
handled = true;
}
}
"enter" | "space" | " " => {
let mut st = key_state.borrow_mut();
st.selected_id = Some(cur_item.node.id.clone());
sel_to_notify = Some(cur_item.node.clone());
if cur_item.node.has_children() {
let mut next_set: HashSet<SharedString> = key_ext_exp
.as_ref()
.map(|v| v.iter().cloned().collect())
.unwrap_or_else(|| st.expanded.clone());
if next_set.contains(&cur_item.node.id) {
next_set.remove(&cur_item.node.id);
} else {
next_set.insert(cur_item.node.id.clone());
st.opened_id = Some(cur_item.node.id.clone());
st.opened_at = t_now;
}
if !is_controlled_exp {
st.expanded = next_set.clone();
}
let mut v: Vec<SharedString> = next_set.into_iter().collect();
v.sort();
exp_to_notify = Some(v);
}
handled = true;
}
_ => {}
}
if handled {
if let (Some(node), Some(cb)) = (sel_to_notify, &key_on_sel) {
cb(&node, window, cx);
}
if let (Some(v), Some(cb)) = (exp_to_notify, &key_on_exp) {
cb(&v, window, cx);
}
window.refresh();
}
})
.child(
div()
.relative()
.w_full()
.flex()
.flex_col()
.when_some(selection_pill, |el, pill| el.child(pill))
.children(rows_els),
)
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flatten_tree_respects_expanded_set_and_depths() {
let nodes = vec![
TreeNode::branch(
"src",
"src",
[
TreeNode::branch("ui", "ui", [TreeNode::leaf("btn", "button.rs")]),
TreeNode::leaf("lib", "lib.rs"),
],
),
TreeNode::leaf("readme", "README.md"),
];
let mut expanded = HashSet::new();
assert_eq!(flatten_tree(&nodes, &expanded).len(), 2);
expanded.insert(SharedString::from("src"));
let rows = flatten_tree(&nodes, &expanded);
assert_eq!(rows.len(), 4);
assert_eq!(rows[1].node.id, "ui");
assert_eq!(rows[1].depth, 2);
assert_eq!(rows[1].parent_id.as_deref(), Some("src"));
expanded.insert(SharedString::from("ui"));
let deep_rows = flatten_tree(&nodes, &expanded);
assert_eq!(deep_rows.len(), 5);
assert_eq!(deep_rows[2].node.id, "btn");
assert_eq!(deep_rows[2].depth, 3);
}
#[test]
fn tree_row_reveal_stagger_caps_at_seven() {
let (a0, x0) = tree_row_reveal_sample(0.05, 0, false);
let (a7, _) = tree_row_reveal_sample(0.20, 7, false);
let (a12, _) = tree_row_reveal_sample(0.20, 12, false);
assert!(a0 > 0.0 && x0 > -6.0);
assert_eq!(a7, a12);
}
}