refactor: consolidate shared ui helpers and prune unused code
This commit is contained in:
+300
-113
@@ -15,6 +15,8 @@
|
||||
//! .on_change(|_selected, _window, _cx| println!("selection changed"));
|
||||
//! ```
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::prelude::FluentBuilder;
|
||||
@@ -71,6 +73,16 @@ impl TreeItem {
|
||||
}
|
||||
}
|
||||
|
||||
/// The row's key: the path-like id its builder passed.
|
||||
pub fn key(&self) -> &ElementId {
|
||||
&self.key
|
||||
}
|
||||
|
||||
/// Whether the row has children and paints a chevron.
|
||||
pub fn is_expandable(&self) -> bool {
|
||||
self.expandable
|
||||
}
|
||||
|
||||
/// Shows a custom icon leading the label.
|
||||
pub fn icon<I>(mut self, icon: I) -> Self
|
||||
where
|
||||
@@ -103,11 +115,299 @@ impl TreeItem {
|
||||
self.disabled = disabled;
|
||||
self
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render_row(
|
||||
&self,
|
||||
cx: &App,
|
||||
index: usize,
|
||||
position_in_set: usize,
|
||||
size_of_set: usize,
|
||||
selected: bool,
|
||||
on_change: &Option<ChangeHandler>,
|
||||
on_disclosure: &Option<DisclosureHandler>,
|
||||
focus: &FocusHandle,
|
||||
) -> AnyElement {
|
||||
let theme = cx.theme();
|
||||
let label_color = selectable_label_color(cx, selected, self.disabled);
|
||||
let disabled = self.disabled;
|
||||
|
||||
let depth = self.depth.min(TREE_MAX_DEPTH) as f32;
|
||||
let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 });
|
||||
|
||||
div()
|
||||
.id((self.key.clone(), "tree-item"))
|
||||
.relative()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.pl(indent)
|
||||
.pr_2()
|
||||
.py_1()
|
||||
.min_h_8()
|
||||
.rounded(theme.radius.sm)
|
||||
.role(Role::TreeItem)
|
||||
.aria_selected(selected)
|
||||
.aria_level(self.depth + 1)
|
||||
.aria_position_in_set(position_in_set)
|
||||
.aria_size_of_set(size_of_set)
|
||||
.when(self.expandable, |row| row.aria_expanded(self.expanded))
|
||||
.map(|row| paint_selectable_row(cx, row, selected, disabled))
|
||||
.when(!disabled, |row| {
|
||||
row.cursor_pointer().on_click({
|
||||
let on_change = on_change.clone();
|
||||
let on_disclosure = on_disclosure.clone();
|
||||
let expandable = self.expandable;
|
||||
let focus = focus.clone();
|
||||
|
||||
move |_, window, cx| {
|
||||
window.focus(&focus, cx);
|
||||
if let Some(on_change) = &on_change {
|
||||
on_change(Some(index), window, cx);
|
||||
}
|
||||
// A folder row toggles with its own click, not just its chevron.
|
||||
if expandable && let Some(on_disclosure) = &on_disclosure {
|
||||
on_disclosure(index, window, cx);
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| {
|
||||
let step = level as f32;
|
||||
div()
|
||||
.absolute()
|
||||
.left(rems(0.75 * (step + 0.5)))
|
||||
.top_0()
|
||||
.bottom_0()
|
||||
.border_l_1()
|
||||
.border_color(theme.colors.border)
|
||||
}))
|
||||
.child(self.render_disclosure(cx, selected))
|
||||
.when_some(
|
||||
self.icon
|
||||
.clone()
|
||||
.or_else(|| (!self.expandable).then(|| icon(IconRole::File))),
|
||||
|row, icon| row.child(icon.size(rems(1.0)).color(label_color)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.text_color(label_color)
|
||||
.child(self.label.clone()),
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement {
|
||||
let theme = cx.theme();
|
||||
let glyph_color = if self.disabled || !selected {
|
||||
theme.colors.muted_foreground
|
||||
} else {
|
||||
theme.colors.primary_foreground
|
||||
};
|
||||
|
||||
// Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders.
|
||||
div()
|
||||
.flex_none()
|
||||
.size_4()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.when(self.expandable, |cell| {
|
||||
cell.child(
|
||||
icon(if self.expanded {
|
||||
IconRole::ChevronDown
|
||||
} else {
|
||||
IconRole::ChevronRight
|
||||
})
|
||||
.size(rems(0.75))
|
||||
.color(glyph_color),
|
||||
)
|
||||
})
|
||||
.into_any_element()
|
||||
}
|
||||
}
|
||||
|
||||
// TreeItem is a data builder, not an element, adopt the combinators explicitly.
|
||||
impl FluentBuilder for TreeItem {}
|
||||
|
||||
/// A nested path node; `flatten_all` turns a forest of these into rows.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TreeItemSeed {
|
||||
/// Path of the node, relative to the worktree root.
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub children: Vec<TreeItemSeed>,
|
||||
}
|
||||
|
||||
impl TreeItemSeed {
|
||||
/// Flattens the seeds into the rows a flat tree renders, honoring `expanded`.
|
||||
///
|
||||
/// Expandable rows carry the folder icon; leaves fall back to the file icon
|
||||
/// the tree paints by default.
|
||||
pub fn flatten_all(seeds: &[TreeItemSeed], expanded: &HashSet<String>) -> Vec<TreeItem> {
|
||||
fn push(
|
||||
seed: &TreeItemSeed,
|
||||
depth: usize,
|
||||
expanded: &HashSet<String>,
|
||||
rows: &mut Vec<TreeItem>,
|
||||
) {
|
||||
let is_expanded = expanded.contains(&seed.id);
|
||||
let mut item = TreeItem::new(seed.id.clone(), seed.label.clone())
|
||||
.depth(depth)
|
||||
.expandable(!seed.children.is_empty())
|
||||
.expanded(is_expanded);
|
||||
if !seed.children.is_empty() {
|
||||
item = item.icon(Icon::named(IconRole::Folder));
|
||||
}
|
||||
rows.push(item);
|
||||
|
||||
if is_expanded {
|
||||
for child in &seed.children {
|
||||
push(child, depth + 1, expanded, rows);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut rows = Vec::new();
|
||||
for seed in seeds {
|
||||
push(seed, 0, expanded, &mut rows);
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Every folder id, for starting with the tree fully expanded.
|
||||
pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet<String> {
|
||||
fn push(seed: &TreeItemSeed, expanded: &mut HashSet<String>) {
|
||||
if !seed.children.is_empty() {
|
||||
expanded.insert(seed.id.clone());
|
||||
for child in &seed.children {
|
||||
push(child, expanded);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut expanded = HashSet::new();
|
||||
for seed in seeds {
|
||||
push(seed, &mut expanded);
|
||||
}
|
||||
expanded
|
||||
}
|
||||
|
||||
/// Builds nested tree items from a flat entry list sorted dirs-first.
|
||||
pub fn from_paths(paths: &[PathBuf]) -> Vec<TreeItemSeed> {
|
||||
// Node indices by full path, so parents resolve in constant time while inserting.
|
||||
let mut index: HashMap<String, usize> = HashMap::new();
|
||||
let mut nodes: Vec<(String, String, Vec<usize>)> = Vec::new();
|
||||
let mut roots: Vec<usize> = Vec::new();
|
||||
|
||||
for entry in paths {
|
||||
let mut parent: Option<usize> = None;
|
||||
let mut path = String::new();
|
||||
for part in entry.components() {
|
||||
let label = part.as_os_str().to_string_lossy().into_owned();
|
||||
path = if path.is_empty() {
|
||||
label.clone()
|
||||
} else {
|
||||
format!("{path}/{label}")
|
||||
};
|
||||
let ix = *index.entry(path.clone()).or_insert_with(|| {
|
||||
let ix = nodes.len();
|
||||
nodes.push((path.clone(), label.clone(), Vec::new()));
|
||||
match parent {
|
||||
Some(parent) => nodes[parent].2.push(ix),
|
||||
None => roots.push(ix),
|
||||
}
|
||||
ix
|
||||
});
|
||||
parent = Some(ix);
|
||||
}
|
||||
}
|
||||
|
||||
fn assemble(ix: usize, nodes: &[(String, String, Vec<usize>)]) -> TreeItemSeed {
|
||||
let (id, label, children) = &nodes[ix];
|
||||
TreeItemSeed {
|
||||
id: id.clone(),
|
||||
label: label.clone(),
|
||||
children: children
|
||||
.iter()
|
||||
.map(|child| assemble(*child, nodes))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
roots.iter().map(|root| assemble(*root, &nodes)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod seed_tests {
|
||||
use super::*;
|
||||
|
||||
fn ids(rows: &[TreeItem]) -> Vec<(String, usize)> {
|
||||
rows.iter()
|
||||
.map(|row| (row.key().to_string(), row.depth))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsed_folders_hide_children() {
|
||||
let seeds = TreeItemSeed::from_paths(&[
|
||||
PathBuf::from("src"),
|
||||
PathBuf::from("src/lib.rs"),
|
||||
PathBuf::from("README.md"),
|
||||
]);
|
||||
|
||||
let rows = TreeItemSeed::flatten_all(&seeds, &HashSet::new());
|
||||
|
||||
assert_eq!(
|
||||
ids(&rows),
|
||||
vec![("src".to_owned(), 0), ("README.md".to_owned(), 0)]
|
||||
);
|
||||
assert!(rows[0].expandable);
|
||||
assert!(!rows[0].expanded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expanding_a_folder_shows_children_in_order() {
|
||||
let seeds = TreeItemSeed::from_paths(&[
|
||||
PathBuf::from("src"),
|
||||
PathBuf::from("src/lib.rs"),
|
||||
PathBuf::from("src/views/mod.rs"),
|
||||
PathBuf::from("README.md"),
|
||||
]);
|
||||
let expanded = HashSet::from(["src".to_owned(), "src/views".to_owned()]);
|
||||
|
||||
let rows = TreeItemSeed::flatten_all(&seeds, &expanded);
|
||||
|
||||
assert_eq!(
|
||||
ids(&rows),
|
||||
vec![
|
||||
("src".to_owned(), 0),
|
||||
("src/lib.rs".to_owned(), 1),
|
||||
("src/views".to_owned(), 1),
|
||||
("src/views/mod.rs".to_owned(), 2),
|
||||
("README.md".to_owned(), 0),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indices_map_to_row_ids() {
|
||||
let seeds = TreeItemSeed::from_paths(&[
|
||||
PathBuf::from("docs"),
|
||||
PathBuf::from("docs/guide.md"),
|
||||
PathBuf::from("README.md"),
|
||||
]);
|
||||
let expanded = HashSet::from(["docs".to_owned()]);
|
||||
let rows = TreeItemSeed::flatten_all(&seeds, &expanded);
|
||||
|
||||
assert_eq!(rows[0].key().to_string(), "docs");
|
||||
assert_eq!(rows[1].key().to_string(), "docs/guide.md");
|
||||
assert_eq!(rows[2].key().to_string(), "README.md");
|
||||
}
|
||||
}
|
||||
|
||||
/// A tree of [`TreeItem`] rows with single selection and disclosure handling.
|
||||
#[derive(IntoElement)]
|
||||
#[must_use]
|
||||
@@ -345,116 +645,3 @@ impl RenderOnce for Tree {
|
||||
.children(rows)
|
||||
}
|
||||
}
|
||||
|
||||
impl TreeItem {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render_row(
|
||||
&self,
|
||||
cx: &App,
|
||||
index: usize,
|
||||
position_in_set: usize,
|
||||
size_of_set: usize,
|
||||
selected: bool,
|
||||
on_change: &Option<ChangeHandler>,
|
||||
on_disclosure: &Option<DisclosureHandler>,
|
||||
focus: &FocusHandle,
|
||||
) -> AnyElement {
|
||||
let theme = cx.theme();
|
||||
let label_color = selectable_label_color(cx, selected, self.disabled);
|
||||
let disabled = self.disabled;
|
||||
|
||||
let depth = self.depth.min(TREE_MAX_DEPTH) as f32;
|
||||
let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 });
|
||||
|
||||
div()
|
||||
.id((self.key.clone(), "tree-item"))
|
||||
.relative()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.pl(indent)
|
||||
.pr_2()
|
||||
.py_1()
|
||||
.min_h_8()
|
||||
.rounded(theme.radius.sm)
|
||||
.role(Role::TreeItem)
|
||||
.aria_selected(selected)
|
||||
.aria_level(self.depth + 1)
|
||||
.aria_position_in_set(position_in_set)
|
||||
.aria_size_of_set(size_of_set)
|
||||
.when(self.expandable, |row| row.aria_expanded(self.expanded))
|
||||
.map(|row| paint_selectable_row(cx, row, selected, disabled))
|
||||
.when(!disabled, |row| {
|
||||
row.cursor_pointer().on_click({
|
||||
let on_change = on_change.clone();
|
||||
let on_disclosure = on_disclosure.clone();
|
||||
let expandable = self.expandable;
|
||||
let focus = focus.clone();
|
||||
|
||||
move |_, window, cx| {
|
||||
window.focus(&focus, cx);
|
||||
if let Some(on_change) = &on_change {
|
||||
on_change(Some(index), window, cx);
|
||||
}
|
||||
// A folder row toggles with its own click, not just its chevron.
|
||||
if expandable && let Some(on_disclosure) = &on_disclosure {
|
||||
on_disclosure(index, window, cx);
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| {
|
||||
let step = level as f32;
|
||||
div()
|
||||
.absolute()
|
||||
.left(rems(0.75 * (step + 0.5)))
|
||||
.top_0()
|
||||
.bottom_0()
|
||||
.border_l_1()
|
||||
.border_color(theme.colors.border)
|
||||
}))
|
||||
.child(self.render_disclosure(cx, selected))
|
||||
.when_some(
|
||||
self.icon
|
||||
.clone()
|
||||
.or_else(|| (!self.expandable).then(|| icon(IconRole::File))),
|
||||
|row, icon| row.child(icon.size(rems(1.0)).color(label_color)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.text_color(label_color)
|
||||
.child(self.label.clone()),
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement {
|
||||
let theme = cx.theme();
|
||||
let glyph_color = if self.disabled || !selected {
|
||||
theme.colors.muted_foreground
|
||||
} else {
|
||||
theme.colors.primary_foreground
|
||||
};
|
||||
|
||||
// Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders.
|
||||
div()
|
||||
.flex_none()
|
||||
.size_4()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.when(self.expandable, |cell| {
|
||||
cell.child(
|
||||
icon(if self.expanded {
|
||||
IconRole::ChevronDown
|
||||
} else {
|
||||
IconRole::ChevronRight
|
||||
})
|
||||
.size(rems(0.75))
|
||||
.color(glyph_color),
|
||||
)
|
||||
})
|
||||
.into_any_element()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user