This commit is contained in:
2026-10-30 14:12:09 +07:00
parent f23c582c16
commit 8be5ac91ec
6 changed files with 790 additions and 3 deletions
+2 -1
View File
@@ -14,5 +14,6 @@ gpui = { workspace = true, features = ["test-support"] }
[features]
default = ["full"]
full = ["list"]
full = ["list", "tree"]
list = []
tree = []
+3
View File
@@ -3,3 +3,6 @@
#[cfg(feature = "list")]
pub mod list;
#[cfg(feature = "tree")]
pub mod tree;
+439
View File
@@ -0,0 +1,439 @@
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, ElementId, FocusHandle, Hsla, InteractiveElement as _, IntoElement,
KeyDownEvent, ParentElement as _, Pixels, RenderOnce, Role, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, div,
};
use gpui_native_icons::{IconRole, icon};
use gpui_native_theme::ActiveTheme as _;
/// The change reporter, fired with the next selection by pointer and keys.
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
/// The disclosure reporter, fired with the toggled row's index.
type DisclosureHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<TreeItem>>;
/// Tree item.
#[derive(Clone)]
pub struct TreeItem {
label: SharedString,
icon: Option<IconRole>,
depth: usize,
expandable: bool,
expanded: bool,
disabled: bool,
}
impl TreeItem {
/// Creates a leaf row with this label at the root depth.
pub fn new<L>(label: L) -> Self
where
L: Into<SharedString>,
{
Self {
label: label.into(),
icon: None,
depth: 0,
expandable: false,
expanded: false,
disabled: false,
}
}
/// Shows an icon leading the label.
pub fn icon(mut self, role: IconRole) -> Self {
self.icon = Some(role);
self
}
/// Nests the row one level per count.
pub fn depth(mut self, depth: usize) -> Self {
self.depth = depth;
self
}
/// Marks the row as having children.
pub fn expandable(mut self, expandable: bool) -> Self {
self.expandable = expandable;
self
}
/// Sets the row's disclosure state.
pub fn expanded(mut self, expanded: bool) -> Self {
self.expanded = expanded;
self
}
/// Renders the row dimmed; clicks and keyboard skip it.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
/// A tree.
#[derive(IntoElement)]
pub struct Tree {
id: ElementId,
selected: Option<usize>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
on_disclosure: Option<DisclosureHandler>,
items: Option<ItemsFn>,
}
impl Tree {
/// Creates a tree with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
selected: None,
a11y_label: None,
on_change: None,
on_disclosure: None,
items: None,
}
}
/// Sets the current selection.
pub fn selected(mut self, selected: Option<usize>) -> Self {
self.selected = selected;
self
}
/// Reports the next selection, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<usize>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Reports the row whose disclosure the user toggled.
pub fn on_disclosure<F>(mut self, handler: F) -> Self
where
F: Fn(usize, &mut Window, &mut App) + 'static,
{
self.on_disclosure = Some(Rc::new(handler));
self
}
/// Sets the visible rows, built fresh each render.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<TreeItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the accessibility label, which defaults to the id.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
struct TreeChrome {
foreground: Hsla,
muted: Hsla,
muted_foreground: Hsla,
primary: Hsla,
primary_foreground: Hsla,
radius_sm: Pixels,
icon_size: Pixels,
padding_x: Pixels,
text_size: Pixels,
/// The row count, for the rows' set-size a11y attributes.
count: usize,
}
impl RenderOnce for Tree {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let chrome = {
let theme = cx.theme();
TreeChrome {
foreground: theme.colors.foreground,
muted: theme.colors.muted,
muted_foreground: theme.colors.muted_foreground,
primary: theme.ramps.primary.base,
primary_foreground: theme.colors.primary_foreground,
radius_sm: theme.radius.sm,
icon_size: theme.sizes.medium.icon_size,
padding_x: theme.sizes.medium.padding_x,
text_size: theme.sizes.medium.text_size,
count: 0,
}
};
let items = match self.items {
Some(build) => build(window, cx),
None => Vec::new(),
};
let selectable: Vec<usize> = items
.iter()
.enumerate()
.filter(|(_, item)| !item.disabled)
.map(|(index, _)| index)
.collect();
// Keyboard focus rides the container across frames.
let focus_handle = window.with_element_namespace(self.id.clone(), |window| {
window.use_keyed_state("tree-focus", cx, |_, cx| cx.focus_handle())
});
let focus = focus_handle.read(cx).clone();
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let chrome = TreeChrome {
count: items.len(),
..chrome
};
let rows: Vec<AnyElement> = items
.iter()
.enumerate()
.map(|(index, item)| {
render_row(
item,
index,
self.selected == Some(index),
&chrome,
&self.on_change,
&self.on_disclosure,
&focus,
)
})
.collect();
div()
.id(self.id)
.flex()
.flex_col()
.gap_0p5()
.text_size(chrome.text_size)
.track_focus(&focus)
.focusable()
.tab_stop(true)
.role(Role::Tree)
.aria_label(label)
.on_key_down({
let selected = self.selected;
let on_change = self.on_change.clone();
let on_disclosure = self.on_disclosure.clone();
move |event: &KeyDownEvent, window, cx| {
match event.keystroke.key.as_str() {
"down" => {
if let Some(next) = adjacent(&selectable, selected, true)
&& Some(next) != selected
&& let Some(on_change) = &on_change
{
on_change(Some(next), window, cx);
}
}
"up" => {
if let Some(next) = adjacent(&selectable, selected, false)
&& Some(next) != selected
&& let Some(on_change) = &on_change
{
on_change(Some(next), window, cx);
}
}
"home" => {
if let Some(first) = selectable.first()
&& selected != Some(*first)
&& let Some(on_change) = &on_change
{
on_change(Some(*first), window, cx);
}
}
"end" => {
if let Some(last) = selectable.last()
&& selected != Some(*last)
&& let Some(on_change) = &on_change
{
on_change(Some(*last), window, cx);
}
}
"left" | "right" => {
let expanding = event.keystroke.key == "right";
if let Some(index) = selected
&& let Some(item) = items.get(index)
&& item.expandable
&& !item.disabled
&& item.expanded != expanding
&& let Some(on_disclosure) = &on_disclosure
{
on_disclosure(index, window, cx);
}
}
_ => return,
}
cx.stop_propagation();
}
})
.children(rows)
}
}
fn render_row(
item: &TreeItem,
index: usize,
selected: bool,
chrome: &TreeChrome,
on_change: &Option<ChangeHandler>,
on_disclosure: &Option<DisclosureHandler>,
focus: &FocusHandle,
) -> AnyElement {
let label_color = row_color(item, selected, chrome);
let disabled = item.disabled;
// One indent step per depth level, on the theme's horizontal padding.
let indent = chrome.padding_x * (item.depth as f32 + 1.0);
div()
.id(("tree-item", index))
.flex()
.items_center()
.gap_2()
.pl(indent)
.pr_2()
.py_1()
.rounded(chrome.radius_sm)
.role(Role::TreeItem)
.aria_selected(selected)
.aria_level(item.depth + 1)
.aria_size_of_set(chrome.count)
.when(item.expandable, |row| row.aria_expanded(item.expanded))
.map(|row| {
if disabled {
row
} else if selected {
row.bg(chrome.primary)
} else {
row.hover(|row| row.bg(chrome.muted))
}
})
.when(!disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
}
})
})
.child(render_disclosure(
item,
index,
disabled,
selected,
chrome,
on_disclosure,
))
.when_some(item.icon, |row, role| {
row.child(icon(role).size(chrome.icon_size).color(label_color))
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(item.label.clone()),
)
.into_any_element()
}
/// The disclosure slot.
fn render_disclosure(
item: &TreeItem,
index: usize,
disabled: bool,
selected: bool,
chrome: &TreeChrome,
on_disclosure: &Option<DisclosureHandler>,
) -> AnyElement {
let glyph_color = if disabled {
chrome.muted_foreground
} else if selected {
chrome.primary_foreground
} else {
chrome.muted_foreground
};
let cell = div()
.flex_none()
.size(chrome.icon_size)
.flex()
.items_center()
.justify_center()
.child(
icon(if item.expanded {
IconRole::ChevronDown
} else {
IconRole::ChevronRight
})
.size(chrome.icon_size * 0.75)
.color(glyph_color),
);
if item.expandable && !disabled {
cell.id(("tree-disclosure", index))
.cursor_pointer()
.on_click({
let on_disclosure = on_disclosure.clone();
move |_, window, cx| {
if let Some(on_disclosure) = &on_disclosure {
on_disclosure(index, window, cx);
}
// The toggle is not a selection: keep it off the row.
cx.stop_propagation();
}
})
.into_any_element()
} else {
cell.into_any_element()
}
}
/// The row's label/icon color.
fn row_color(item: &TreeItem, selected: bool, chrome: &TreeChrome) -> Hsla {
if item.disabled {
chrome.muted_foreground
} else if selected {
chrome.primary_foreground
} else {
chrome.foreground
}
}
/// The next selectable row in the direction.
fn adjacent(selectable: &[usize], selected: Option<usize>, forward: bool) -> Option<usize> {
if forward {
selectable
.iter()
.copied()
.find(|index| Some(*index) > selected)
} else {
selectable
.iter()
.copied()
.rev()
.find(|index| Some(*index) < selected)
}
}
+191
View File
@@ -0,0 +1,191 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
Context, IntoElement, Modifiers, MouseButton, ParentElement as _, Render, Styled as _,
TestAppContext, VisualTestContext, Window, WindowHandle, div, point, px,
};
use gpui_native_data::tree::{Tree, TreeItem};
use gpui_native_theme::Theme;
type Changes = Rc<RefCell<Vec<Option<usize>>>>;
type Disclosures = Rc<RefCell<Vec<usize>>>;
struct Harness {
selected: Option<usize>,
changes: Changes,
disclosures: Disclosures,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let disclosures = self.disclosures.clone();
let view = cx.entity();
let change_view = view.clone();
div().size_full().child(
Tree::new("test-tree")
.selected(self.selected)
.on_change(move |next, _, cx| {
changes.borrow_mut().push(next);
change_view.update(cx, |harness, cx| {
harness.selected = next;
cx.notify();
});
})
.on_disclosure(move |index, _, cx| {
disclosures.borrow_mut().push(index);
view.update(cx, |_, cx| cx.notify());
})
.items(|_, _| {
vec![
TreeItem::new("Root")
.depth(0)
.expandable(true)
.expanded(true),
TreeItem::new("Child").depth(1),
TreeItem::new("Collapsed").depth(0).expandable(true),
TreeItem::new("Untouchable").depth(1).disabled(true),
TreeItem::new("Last").depth(0),
]
}),
)
}
}
/// Rows paint at the top-left, one per ~34 px band (same rhythm as the
/// list), so clicks at `(50, 16/48/80/112/144)` land on Root / Child /
/// Collapsed / the disabled Untouchable / Last. Each expandable row leads
/// with a 16 px disclosure slot at its indent — a click at `(24, y)` hits
/// row 0's chevron.
fn tree_window() -> (
TestAppContext,
VisualTestContext,
WindowHandle<Harness>,
Changes,
Disclosures,
) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let disclosures = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let harness_disclosures = disclosures.clone();
let window = cx.add_window(move |_, _| Harness {
selected: None,
changes: harness_changes,
disclosures: harness_disclosures,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, window, changes, disclosures)
}
fn draw(visual: &mut VisualTestContext) {
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
fn click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
visual.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
}
#[test]
fn clicking_a_row_selects_it_and_hands_the_tree_the_keyboard() {
let (_cx, mut visual, _window, changes, disclosures) = tree_window();
click(&mut visual, point(px(50.), px(16.)));
assert_eq!(*changes.borrow(), vec![Some(0)]);
assert!(disclosures.borrow().is_empty());
// The click focused the tree; arrows move within the visible rows.
visual.simulate_keystrokes("down");
draw(&mut visual);
assert_eq!(*changes.borrow(), vec![Some(0), Some(1)]);
}
#[test]
fn clicking_the_disclosure_toggles_without_selecting() {
let (_cx, mut visual, _window, changes, disclosures) = tree_window();
// Row 0's chevron, not its label.
click(&mut visual, point(px(24.), px(16.)));
draw(&mut visual);
assert_eq!(*disclosures.borrow(), vec![0]);
assert!(
changes.borrow().is_empty(),
"a disclosure is not a selection"
);
}
#[test]
fn arrow_right_expands_and_left_collapses_the_selected_row() {
let (_cx, mut visual, _window, changes, disclosures) = tree_window();
click(&mut visual, point(px(50.), px(16.))); // Root: expanded expandable
visual.simulate_keystrokes("left"); // collapse → reports
visual.simulate_keystrokes("right"); // still collapsed per the caller → nothing yet
visual.simulate_keystrokes("down"); // Child: a leaf → arrows are inert
visual.simulate_keystrokes("right");
visual.simulate_keystrokes("left");
draw(&mut visual);
assert_eq!(*disclosures.borrow(), vec![0]);
assert_eq!(
*changes.borrow(),
vec![Some(0), Some(1)],
"disclosure keys never change the selection"
);
// Select the collapsed expandable row and expand it.
click(&mut visual, point(px(50.), px(80.)));
visual.simulate_keystrokes("right");
draw(&mut visual);
assert_eq!(*disclosures.borrow(), vec![0, 2]);
}
#[test]
fn keyboard_navigation_skips_disabled_rows_and_never_wraps() {
let (_cx, mut visual, _window, changes, _disclosures) = tree_window();
click(&mut visual, point(px(50.), px(16.)));
visual.simulate_keystrokes("down"); // Two
visual.simulate_keystrokes("down"); // Collapsed — selectable, not disabled
visual.simulate_keystrokes("down"); // over the disabled row → Last
visual.simulate_keystrokes("down"); // last selectable; no wrap
draw(&mut visual);
assert_eq!(*changes.borrow(), vec![Some(0), Some(1), Some(2), Some(4)]);
visual.simulate_keystrokes("home");
visual.simulate_keystrokes("end");
visual.simulate_keystrokes("up"); // over the disabled row
draw(&mut visual);
assert_eq!(
*changes.borrow(),
vec![
Some(0),
Some(1),
Some(2),
Some(4),
Some(0),
Some(4),
Some(2)
]
);
}
#[test]
fn disclosure_keys_skip_disabled_and_unselected_rows() {
let (_cx, mut visual, _window, changes, disclosures) = tree_window();
// Focus through the first row, then park the selection on the leaf.
click(&mut visual, point(px(50.), px(16.)));
visual.simulate_keystrokes("down"); // Child (leaf), focused tree
visual.simulate_keystrokes("left"); // leaf: no disclosure
visual.simulate_keystrokes("right"); // leaf: no disclosure
draw(&mut visual);
assert!(disclosures.borrow().is_empty());
assert_eq!(*changes.borrow(), vec![Some(0), Some(1)]);
}