use std::{
cell::RefCell,
cmp::Ordering,
collections::{HashMap, HashSet},
rc::Rc,
};
use arc_motion::{
CubicBezier, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window,
base::StyledExt as _, canvas, div, point, prelude::*, px,
};
pub const TREE_TABLE_ROW_HEIGHT_PX: f32 = 38.0;
pub const TREE_TABLE_INDENT_PX: f32 = 18.0;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TreeTableAlign {
Start,
End,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TreeTableSortDir {
Ascending,
Descending,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TreeTableSort {
pub column_id: SharedString,
pub direction: TreeTableSortDir,
}
impl TreeTableSort {
pub fn ascending(column_id: impl Into<SharedString>) -> Self {
Self {
column_id: column_id.into(),
direction: TreeTableSortDir::Ascending,
}
}
pub fn descending(column_id: impl Into<SharedString>) -> Self {
Self {
column_id: column_id.into(),
direction: TreeTableSortDir::Descending,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum TreeTableCellValue {
Text(SharedString),
Number(f64),
}
impl TreeTableCellValue {
pub fn display_text(&self) -> SharedString {
match self {
Self::Text(s) => s.clone(),
Self::Number(n) => {
if (n.fract()).abs() < 1e-9 {
SharedString::from(format!("{}", *n as i64))
} else {
SharedString::from(format!("{n:.1}"))
}
}
}
}
fn cmp_value(&self, other: &Self) -> Ordering {
match (self, other) {
(Self::Number(a), Self::Number(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
_ => self
.display_text()
.to_lowercase()
.cmp(&other.display_text().to_lowercase()),
}
}
}
impl From<&str> for TreeTableCellValue {
fn from(s: &str) -> Self {
Self::Text(SharedString::from(s.to_string()))
}
}
impl From<String> for TreeTableCellValue {
fn from(s: String) -> Self {
Self::Text(SharedString::from(s))
}
}
impl From<f64> for TreeTableCellValue {
fn from(n: f64) -> Self {
Self::Number(n)
}
}
#[derive(Clone, Debug)]
pub struct TreeTableColumn {
pub id: SharedString,
pub header: SharedString,
pub sortable: bool,
pub width: Option<f32>,
pub align: TreeTableAlign,
}
impl TreeTableColumn {
pub fn new(id: impl Into<SharedString>, header: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
header: header.into(),
sortable: false,
width: None,
align: TreeTableAlign::Start,
}
}
pub fn sortable(mut self, sortable: bool) -> Self {
self.sortable = sortable;
self
}
pub fn width(mut self, width_px: f32) -> Self {
self.width = Some(width_px);
self
}
pub fn align(mut self, align: TreeTableAlign) -> Self {
self.align = align;
self
}
}
#[derive(Clone, Debug)]
pub struct TreeTableRow {
pub id: SharedString,
pub cells: HashMap<SharedString, TreeTableCellValue>,
pub children: Vec<TreeTableRow>,
}
impl TreeTableRow {
pub fn new(id: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
cells: HashMap::new(),
children: Vec::new(),
}
}
pub fn cell(
mut self,
column_id: impl Into<SharedString>,
value: impl Into<TreeTableCellValue>,
) -> Self {
self.cells.insert(column_id.into(), value.into());
self
}
pub fn children(mut self, children: impl IntoIterator<Item = TreeTableRow>) -> Self {
self.children = children.into_iter().collect();
self
}
pub fn has_children(&self) -> bool {
!self.children.is_empty()
}
}
#[derive(Clone, Debug)]
pub struct VisibleTreeTableRow {
pub row: TreeTableRow,
pub depth: usize,
pub parent_id: Option<SharedString>,
pub expandable: bool,
pub expanded: bool,
pub sibling_index: usize,
}
pub fn collect_tree_table_expandable_ids(rows: &[TreeTableRow]) -> Vec<SharedString> {
let mut out = Vec::new();
fn visit(list: &[TreeTableRow], out: &mut Vec<SharedString>) {
for r in list {
if !r.children.is_empty() {
out.push(r.id.clone());
visit(&r.children, out);
}
}
}
visit(rows, &mut out);
out
}
pub fn flatten_tree_table_rows(
rows: &[TreeTableRow],
expanded: &HashSet<SharedString>,
sort: Option<&TreeTableSort>,
) -> Vec<VisibleTreeTableRow> {
let mut out = Vec::new();
fn walk(
list: &[TreeTableRow],
depth: usize,
parent_id: Option<&SharedString>,
expanded: &HashSet<SharedString>,
sort: Option<&TreeTableSort>,
out: &mut Vec<VisibleTreeTableRow>,
) {
let mut ordered: Vec<&TreeTableRow> = list.iter().collect();
if let Some(s) = sort {
let sign = match s.direction {
TreeTableSortDir::Ascending => 1i8,
TreeTableSortDir::Descending => -1i8,
};
ordered.sort_by(|a, b| {
let ord = match (a.cells.get(&s.column_id), b.cells.get(&s.column_id)) {
(Some(va), Some(vb)) => va.cmp_value(vb),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
};
if sign > 0 { ord } else { ord.reverse() }
});
}
for (idx, row) in ordered.into_iter().enumerate() {
let expandable = !row.children.is_empty();
let is_open = expandable && expanded.contains(&row.id);
out.push(VisibleTreeTableRow {
row: row.clone(),
depth,
parent_id: parent_id.cloned(),
expandable,
expanded: is_open,
sibling_index: idx,
});
if is_open {
walk(&row.children, depth + 1, Some(&row.id), expanded, sort, out);
}
}
}
walk(rows, 0, None, expanded, sort, &mut out);
out
}
pub fn normalize_tree_table_selection(
rows: &[TreeTableRow],
selected: &HashSet<SharedString>,
) -> (HashSet<SharedString>, HashSet<SharedString>) {
let mut normalized = selected.clone();
let mut mixed = HashSet::new();
fn settle(
row: &TreeTableRow,
normalized: &mut HashSet<SharedString>,
mixed: &mut HashSet<SharedString>,
) -> (bool, bool) {
if row.children.is_empty() {
let on = normalized.contains(&row.id);
return (on, on);
}
let mut all_on = true;
let mut any_on = false;
for kid in &row.children {
let (kid_all, kid_any) = settle(kid, normalized, mixed);
all_on &= kid_all;
any_on |= kid_any;
}
if all_on {
normalized.insert(row.id.clone());
} else {
normalized.remove(&row.id);
if any_on {
mixed.insert(row.id.clone());
}
}
(all_on, any_on)
}
for r in rows {
settle(r, &mut normalized, &mut mixed);
}
(normalized, mixed)
}
fn collect_subtree_ids(rows: &[TreeTableRow], target: &SharedString) -> Vec<SharedString> {
fn gather(row: &TreeTableRow, out: &mut Vec<SharedString>) {
out.push(row.id.clone());
for kid in &row.children {
gather(kid, out);
}
}
fn find(list: &[TreeTableRow], target: &SharedString, out: &mut Vec<SharedString>) -> bool {
for r in list {
if &r.id == target {
gather(r, out);
return true;
}
if find(&r.children, target, out) {
return true;
}
}
false
}
let mut out = Vec::new();
find(rows, target, &mut out);
out
}
fn collect_all_ids(rows: &[TreeTableRow]) -> Vec<SharedString> {
let mut out = Vec::new();
fn visit(list: &[TreeTableRow], out: &mut Vec<SharedString>) {
for r in list {
out.push(r.id.clone());
visit(&r.children, out);
}
}
visit(rows, &mut out);
out
}
fn paint_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let (c, s) = (rad.cos(), rad.sin());
let rot = |dx: f32, dy: f32| point(px(cx + dx * c - dy * s), px(cy + dx * s + dy * c));
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);
}
}
fn paint_sort_arrow(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let (c, s) = (rad.cos(), rad.sin());
let rot = |dx: f32, dy: f32| point(px(cx + dx * c - dy * s), px(cy + dx * s + dy * c));
let mut shaft = PathBuilder::stroke(px(1.6));
shaft.move_to(rot(0.0, 4.5));
shaft.line_to(rot(0.0, -4.5));
if let Ok(p) = shaft.build() {
window.paint_path(p, color);
}
let mut head = PathBuilder::stroke(px(1.6));
head.move_to(rot(-3.2, -1.2));
head.line_to(rot(0.0, -4.5));
head.line_to(rot(3.2, -1.2));
if let Ok(p) = head.build() {
window.paint_path(p, color);
}
}
fn paint_tri_checkbox(cx: f32, cy: f32, checked: bool, mixed: bool, fg: Hsla, window: &mut Window) {
if !checked && !mixed {
return;
}
let mut pb = PathBuilder::stroke(px(1.8));
if mixed {
pb.move_to(point(px(cx - 4.0), px(cy)));
pb.line_to(point(px(cx + 4.0), px(cy)));
} else {
pb.move_to(point(px(cx - 4.2), px(cy + 0.4)));
pb.line_to(point(px(cx - 1.2), px(cy + 3.4)));
pb.line_to(point(px(cx + 4.6), px(cy - 3.2)));
}
if let Ok(path) = pb.build() {
window.paint_path(path, fg);
}
}
type IdsCallback = Rc<dyn Fn(&Vec<SharedString>, &mut Window, &mut App)>;
type SortCallback = Rc<dyn Fn(&Option<TreeTableSort>, &mut Window, &mut App)>;
type ActivateCallback = Rc<dyn Fn(&TreeTableRow, &mut Window, &mut App)>;
#[derive(Clone)]
struct TreeTableInternal {
expanded: HashSet<SharedString>,
selected: HashSet<SharedString>,
sort: Option<TreeTableSort>,
focused_id: Option<SharedString>,
hovered_id: Option<SharedString>,
opened_parent_id: Option<SharedString>,
opened_at: f64,
focus_handle: FocusHandle,
}
#[derive(IntoElement)]
pub struct TreeTable {
id: ElementId,
label: SharedString,
rows: Vec<TreeTableRow>,
columns: Vec<TreeTableColumn>,
selectable: bool,
default_expanded: Vec<SharedString>,
expanded_override: Option<Vec<SharedString>>,
default_selected: Vec<SharedString>,
selected_override: Option<Vec<SharedString>>,
default_sort: Option<TreeTableSort>,
sort_override: Option<Option<TreeTableSort>>,
empty_message: SharedString,
on_expanded_change: Option<IdsCallback>,
on_selected_change: Option<IdsCallback>,
on_sort_change: Option<SortCallback>,
on_row_activate: Option<ActivateCallback>,
}
impl TreeTable {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
columns: impl IntoIterator<Item = TreeTableColumn>,
rows: impl IntoIterator<Item = TreeTableRow>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
rows: rows.into_iter().collect(),
columns: columns.into_iter().collect(),
selectable: false,
default_expanded: Vec::new(),
expanded_override: None,
default_selected: Vec::new(),
selected_override: None,
default_sort: None,
sort_override: None,
empty_message: SharedString::from("No rows to display"),
on_expanded_change: None,
on_selected_change: None,
on_sort_change: None,
on_row_activate: None,
}
}
pub fn selectable(mut self, selectable: bool) -> Self {
self.selectable = selectable;
self
}
pub fn default_expanded(
mut self,
ids: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.default_expanded = ids.into_iter().map(Into::into).collect();
self
}
pub fn expanded(mut self, ids: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
self.expanded_override = Some(ids.into_iter().map(Into::into).collect());
self
}
pub fn default_selected(
mut self,
ids: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.default_selected = ids.into_iter().map(Into::into).collect();
self
}
pub fn selected(mut self, ids: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
self.selected_override = Some(ids.into_iter().map(Into::into).collect());
self
}
pub fn default_sort(mut self, sort: TreeTableSort) -> Self {
self.default_sort = Some(sort);
self
}
pub fn sort(mut self, sort: Option<TreeTableSort>) -> Self {
self.sort_override = Some(sort);
self
}
pub fn empty_message(mut self, message: impl Into<SharedString>) -> Self {
self.empty_message = message.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_selected_change(
mut self,
cb: impl Fn(&Vec<SharedString>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_selected_change = Some(Rc::new(cb));
self
}
pub fn on_sort_change(
mut self,
cb: impl Fn(&Option<TreeTableSort>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_sort_change = Some(Rc::new(cb));
self
}
pub fn on_row_activate(
mut self,
cb: impl Fn(&TreeTableRow, &mut Window, &mut App) + 'static,
) -> Self {
self.on_row_activate = Some(Rc::new(cb));
self
}
}
impl RenderOnce for TreeTable {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let state_cell = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), SharedString::from("tt-state")),
cx,
|_, cx| {
Rc::new(RefCell::new(TreeTableInternal {
expanded: self.default_expanded.iter().cloned().collect(),
selected: self.default_selected.iter().cloned().collect(),
sort: self.default_sort.clone(),
focused_id: self.rows.first().map(|r| r.id.clone()),
hovered_id: None,
opened_parent_id: None,
opened_at: now - 1.0,
focus_handle: cx.focus_handle(),
}))
},
)
.read(cx)
.clone();
let exp_controlled = self.expanded_override.is_some();
let sel_controlled = self.selected_override.is_some();
let sort_controlled = self.sort_override.is_some();
let (
expanded_set,
raw_selected,
active_sort,
focused_id,
hovered_id,
opened_parent,
opened_elapsed,
focus_handle,
) = {
let mut st = state_cell.borrow_mut();
if let Some(ref ov) = self.expanded_override {
st.expanded = ov.iter().cloned().collect();
}
if let Some(ref ov) = self.selected_override {
st.selected = ov.iter().cloned().collect();
}
if let Some(ref ov) = self.sort_override {
st.sort = ov.clone();
}
let dt = (now - st.opened_at).max(0.0);
if !reduced && st.opened_parent_id.is_some() && dt < 0.45 {
window.request_animation_frame();
} else if dt >= 0.45 {
st.opened_parent_id = None;
}
(
st.expanded.clone(),
st.selected.clone(),
st.sort.clone(),
st.focused_id.clone(),
st.hovered_id.clone(),
st.opened_parent_id.clone(),
dt,
st.focus_handle.clone(),
)
};
let visible = flatten_tree_table_rows(&self.rows, &expanded_set, active_sort.as_ref());
let (selected_set, mixed_set) = normalize_tree_table_selection(&self.rows, &raw_selected);
let all_ids = collect_all_ids(&self.rows);
let all_checked = !all_ids.is_empty() && all_ids.iter().all(|id| selected_set.contains(id));
let some_checked = !all_checked && all_ids.iter().any(|id| selected_set.contains(id));
let header_bg = colors.surface_muted;
let row_hover_bg = oklab_mix(colors.foreground, colors.surface, 0.035);
let row_selected_bg = oklab_mix(colors.accent, colors.surface, 0.08);
let guide_color = colors.border_subtle;
let mut header_row = div()
.w_full()
.h(px(36.0))
.px(Spacing::S3)
.bg(header_bg)
.border_b_1()
.border_color(colors.border)
.flex()
.flex_row()
.items_center()
.gap(Spacing::S3);
if self.selectable {
let st_all = state_cell.clone();
let rows_all = self.rows.clone();
let cb_sel_all = self.on_selected_change.clone();
let box_bg = if all_checked || some_checked {
colors.accent
} else {
colors.surface
};
let box_border = if all_checked || some_checked {
colors.accent
} else {
colors.border_strong
};
let fg_on_acc = colors.accent_foreground;
header_row = header_row.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from("tt-select-all"),
))
.w(px(28.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let next_vec: Vec<SharedString> = if all_checked {
Vec::new()
} else {
collect_all_ids(&rows_all)
};
if !sel_controlled {
st_all.borrow_mut().selected = next_vec.iter().cloned().collect();
}
if let Some(ref cb) = cb_sel_all {
cb(&next_vec, window, cx);
}
window.refresh();
})
.child(
div()
.w(px(16.0))
.h(px(16.0))
.rounded(px(4.0))
.border_1()
.border_color(box_border)
.bg(box_bg)
.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_tri_checkbox(
cx_p,
cy_p,
all_checked,
some_checked,
fg_on_acc,
window,
);
},
)
.size_full(),
),
),
);
}
for col in &self.columns {
let is_sorted = active_sort.as_ref().is_some_and(|s| s.column_id == col.id);
let is_desc = active_sort.as_ref().is_some_and(|s| {
s.column_id == col.id && s.direction == TreeTableSortDir::Descending
});
let arrow_angle = if reduced {
if is_desc { 180.0 } else { 0.0 }
} else {
arc_spring_with_options(
ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("tt-sort-{}", col.id)),
),
if is_desc { 180.0 } else { 0.0 },
SpringOptions::new(SpringSpec::visual(0.22, 0.0))
.with_initial_value(if is_desc { 180.0 } else { 0.0 }),
window,
cx,
)
.value
};
let mut cell = div()
.min_w(px(0.0))
.flex()
.flex_row()
.items_center()
.gap(px(5.0))
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(if is_sorted {
colors.foreground
} else {
colors.text_muted
});
if let Some(w) = col.width {
cell = cell.w(px(w)).flex_none();
} else {
cell = cell.flex_1();
}
if matches!(col.align, TreeTableAlign::End) {
cell = cell.justify_end();
}
let header_cell: AnyElement = if col.sortable {
let st_sort = state_cell.clone();
let col_id = col.id.clone();
let cb_sort = self.on_sort_change.clone();
let arrow_col = if is_sorted {
colors.foreground
} else {
colors.text_muted.opacity(0.4)
};
cell.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("tt-col-{}", col.id)),
))
.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let next = {
let cur = st_sort.borrow().sort.clone();
match cur {
Some(ref s) if s.column_id == col_id => match s.direction {
TreeTableSortDir::Ascending => {
Some(TreeTableSort::descending(col_id.clone()))
}
TreeTableSortDir::Descending => None,
},
_ => Some(TreeTableSort::ascending(col_id.clone())),
}
};
if !sort_controlled {
st_sort.borrow_mut().sort = next.clone();
}
if let Some(ref cb) = cb_sort {
cb(&next, window, cx);
}
window.refresh();
})
.child(col.header.clone())
.child(
div().w(px(14.0)).h(px(14.0)).flex_none().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_sort_arrow(cx_p, cy_p, arrow_angle, arrow_col, window);
},
)
.size_full(),
),
)
.into_any_element()
} else {
cell.child(col.header.clone()).into_any_element()
};
header_row = header_row.child(header_cell);
}
let mut body = div().w_full().flex().flex_col();
if visible.is_empty() {
body = body.child(
div()
.w_full()
.py(Spacing::S8)
.text_center()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.child(self.empty_message.clone()),
);
} else {
for item in &visible {
let row_id = item.row.id.clone();
let is_selected = selected_set.contains(&row_id);
let is_mixed = mixed_set.contains(&row_id);
let is_hovered = hovered_id.as_ref() == Some(&row_id);
let is_focused = focused_id.as_ref() == Some(&row_id);
let reveal_alpha = if !reduced
&& opened_parent.as_ref() == item.parent_id.as_ref()
&& item.parent_id.is_some()
{
let delay = (item.sibling_index.min(7) as f64) * 0.035;
let local = (opened_elapsed - delay).max(0.0);
let t = (local / 0.22).clamp(0.0, 1.0) as f32;
CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
} else {
1.0
};
let row_bg = if is_selected {
row_selected_bg
} else if is_hovered {
row_hover_bg
} else {
colors.surface
};
let chevron_angle = if reduced {
if item.expanded { 90.0 } else { 0.0 }
} else {
arc_spring_with_options(
ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("tt-chev-{row_id}")),
),
if item.expanded { 90.0 } else { 0.0 },
SpringOptions::new(SpringSpec::visual(0.22, 0.0))
.with_initial_value(if item.expanded { 90.0 } else { 0.0 }),
window,
cx,
)
.value
};
let st_hover = state_cell.clone();
let rid_hover = row_id.clone();
let st_click = state_cell.clone();
let row_click = item.row.clone();
let expandable_click = item.expandable;
let cb_exp_click = self.on_expanded_change.clone();
let cb_act_click = self.on_row_activate.clone();
let fh_click = focus_handle.clone();
let mut row_el = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("tt-row-{row_id}")),
))
.role(Role::Row)
.w_full()
.min_h(px(TREE_TABLE_ROW_HEIGHT_PX))
.px(Spacing::S3)
.bg(row_bg)
.border_b_1()
.border_color(colors.border_subtle)
.opacity(reveal_alpha)
.flex()
.flex_row()
.items_center()
.gap(Spacing::S3)
.cursor_pointer()
.when(is_focused, |el| el.border_l_2().border_color(colors.accent))
.on_hover(move |hovered, window, _| {
let mut st = st_hover.borrow_mut();
if *hovered {
st.hovered_id = Some(rid_hover.clone());
} else if st.hovered_id.as_ref() == Some(&rid_hover) {
st.hovered_id = None;
}
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
fh_click.focus(window, cx);
st_click.borrow_mut().focused_id = Some(row_click.id.clone());
if expandable_click {
let next_vec: Vec<SharedString> = {
let mut st = st_click.borrow_mut();
if st.expanded.contains(&row_click.id) {
st.expanded.remove(&row_click.id);
} else {
st.expanded.insert(row_click.id.clone());
st.opened_parent_id = Some(row_click.id.clone());
st.opened_at = motion_now(cx);
}
st.expanded.iter().cloned().collect()
};
if exp_controlled {
}
if let Some(ref cb) = cb_exp_click {
cb(&next_vec, window, cx);
}
} else if let Some(ref cb) = cb_act_click {
cb(&row_click, window, cx);
}
window.refresh();
});
if self.selectable {
let st_chk = state_cell.clone();
let rid_chk = row_id.clone();
let rows_chk = self.rows.clone();
let cb_sel = self.on_selected_change.clone();
let box_bg = if is_selected || is_mixed {
colors.accent
} else {
colors.surface
};
let box_border = if is_selected || is_mixed {
colors.accent
} else {
colors.border_strong
};
let fg_on_acc = colors.accent_foreground;
row_el = row_el.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("tt-chk-{row_id}")),
))
.w(px(28.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
let sub = collect_subtree_ids(&rows_chk, &rid_chk);
let next_set = {
let mut cur = st_chk.borrow().selected.clone();
let turn_on = !is_selected;
for id in sub {
if turn_on {
cur.insert(id);
} else {
cur.remove(&id);
}
}
normalize_tree_table_selection(&rows_chk, &cur).0
};
let next_vec: Vec<SharedString> =
next_set.iter().cloned().collect();
if !sel_controlled {
st_chk.borrow_mut().selected = next_set;
}
if let Some(ref cb) = cb_sel {
cb(&next_vec, window, cx);
}
window.refresh();
})
.child(
div()
.w(px(16.0))
.h(px(16.0))
.rounded(px(4.0))
.border_1()
.border_color(box_border)
.bg(box_bg)
.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_tri_checkbox(
cx_p,
cy_p,
is_selected,
is_mixed,
fg_on_acc,
window,
);
},
)
.size_full(),
),
),
);
}
for (col_idx, col) in self.columns.iter().enumerate() {
let text = item
.row
.cells
.get(&col.id)
.map(TreeTableCellValue::display_text)
.unwrap_or_default();
let mut cell = div()
.min_w(px(0.0))
.flex()
.flex_row()
.items_center()
.text_size(Typography::TEXT_SM)
.text_color(if col_idx == 0 {
colors.foreground
} else {
colors.text_secondary
});
if let Some(w) = col.width {
cell = cell.w(px(w)).flex_none();
} else {
cell = cell.flex_1();
}
if matches!(col.align, TreeTableAlign::End) {
cell = cell.justify_end();
}
if col_idx == 0 {
let mut tree_prefix = div()
.relative()
.flex()
.flex_row()
.items_center()
.h(px(TREE_TABLE_ROW_HEIGHT_PX))
.pl(px(item.depth as f32 * TREE_TABLE_INDENT_PX));
for level in 0..item.depth {
tree_prefix = tree_prefix.child(
div()
.absolute()
.left(px(level as f32 * TREE_TABLE_INDENT_PX + 11.0))
.top_0()
.bottom_0()
.w(px(1.0))
.bg(guide_color),
);
}
let chev_col = colors.text_muted;
let chevron_box: AnyElement = if item.expandable {
div()
.w(px(22.0))
.h(px(22.0))
.mr(px(4.0))
.flex_none()
.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_chevron(
cx_p,
cy_p,
chevron_angle,
chev_col,
window,
);
},
)
.size_full(),
)
.into_any_element()
} else {
div().w(px(22.0)).mr(px(4.0)).flex_none().into_any_element()
};
cell = cell.child(tree_prefix.child(chevron_box)).child(
div()
.flex_1()
.min_w(px(0.0))
.truncate()
.when(item.expandable, |el| el.font_medium())
.child(text),
);
} else {
cell = cell.child(div().truncate().child(text));
}
row_el = row_el.child(cell);
}
body = body.child(row_el);
}
}
let st_key = state_cell.clone();
let vis_key = visible.clone();
let rows_key = self.rows.clone();
let cb_exp_key = self.on_expanded_change.clone();
let cb_sel_key = self.on_selected_change.clone();
let cb_act_key = self.on_row_activate.clone();
let selectable_key = self.selectable;
div()
.id(self.id)
.role(Role::Grid)
.aria_label(self.label)
.track_focus(&focus_handle)
.w_full()
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.overflow_hidden()
.on_key_down(move |ev: &KeyDownEvent, window, cx| {
if vis_key.is_empty() {
return;
}
let cur_idx = {
let st = st_key.borrow();
st.focused_id
.as_ref()
.and_then(|id| vis_key.iter().position(|v| &v.row.id == id))
.unwrap_or(0)
};
let cur = &vis_key[cur_idx];
match ev.keystroke.key.as_str() {
"down" => {
let next = (cur_idx + 1).min(vis_key.len() - 1);
st_key.borrow_mut().focused_id = Some(vis_key[next].row.id.clone());
window.refresh();
}
"up" => {
let next = cur_idx.saturating_sub(1);
st_key.borrow_mut().focused_id = Some(vis_key[next].row.id.clone());
window.refresh();
}
"home" => {
st_key.borrow_mut().focused_id = Some(vis_key[0].row.id.clone());
window.refresh();
}
"end" => {
st_key.borrow_mut().focused_id =
Some(vis_key[vis_key.len() - 1].row.id.clone());
window.refresh();
}
"right" => {
if cur.expandable && !cur.expanded {
let next_vec = {
let mut st = st_key.borrow_mut();
st.expanded.insert(cur.row.id.clone());
st.opened_parent_id = Some(cur.row.id.clone());
st.opened_at = motion_now(cx);
st.expanded.iter().cloned().collect::<Vec<_>>()
};
if let Some(ref cb) = cb_exp_key {
cb(&next_vec, window, cx);
}
window.refresh();
} else if cur.expanded && cur_idx + 1 < vis_key.len() {
st_key.borrow_mut().focused_id =
Some(vis_key[cur_idx + 1].row.id.clone());
window.refresh();
}
}
"left" => {
if cur.expandable && cur.expanded {
let next_vec = {
let mut st = st_key.borrow_mut();
st.expanded.remove(&cur.row.id);
st.expanded.iter().cloned().collect::<Vec<_>>()
};
if let Some(ref cb) = cb_exp_key {
cb(&next_vec, window, cx);
}
window.refresh();
} else if let Some(ref pid) = cur.parent_id {
st_key.borrow_mut().focused_id = Some(pid.clone());
window.refresh();
}
}
"space" if selectable_key => {
let sub = collect_subtree_ids(&rows_key, &cur.row.id);
let next_set = {
let mut cur_sel = st_key.borrow().selected.clone();
let on = !cur_sel.contains(&cur.row.id);
for id in sub {
if on {
cur_sel.insert(id);
} else {
cur_sel.remove(&id);
}
}
normalize_tree_table_selection(&rows_key, &cur_sel).0
};
let next_vec: Vec<SharedString> = next_set.iter().cloned().collect();
if !sel_controlled {
st_key.borrow_mut().selected = next_set;
}
if let Some(ref cb) = cb_sel_key {
cb(&next_vec, window, cx);
}
window.refresh();
}
"enter" => {
if cur.expandable {
let next_vec = {
let mut st = st_key.borrow_mut();
if st.expanded.contains(&cur.row.id) {
st.expanded.remove(&cur.row.id);
} else {
st.expanded.insert(cur.row.id.clone());
st.opened_parent_id = Some(cur.row.id.clone());
st.opened_at = motion_now(cx);
}
st.expanded.iter().cloned().collect::<Vec<_>>()
};
if let Some(ref cb) = cb_exp_key {
cb(&next_vec, window, cx);
}
} else if let Some(ref cb) = cb_act_key {
cb(&cur.row, window, cx);
}
window.refresh();
}
"*" => {
let siblings: Vec<SharedString> = vis_key
.iter()
.filter(|v| v.parent_id == cur.parent_id && v.expandable)
.map(|v| v.row.id.clone())
.collect();
let next_vec = {
let mut st = st_key.borrow_mut();
for sid in siblings {
st.expanded.insert(sid);
}
st.expanded.iter().cloned().collect::<Vec<_>>()
};
if let Some(ref cb) = cb_exp_key {
cb(&next_vec, window, cx);
}
window.refresh();
}
_ => {}
}
})
.child(header_row)
.child(body)
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_rows() -> Vec<TreeTableRow> {
vec![
TreeTableRow::new("eng")
.cell("name", "Engineering")
.cell("headcount", 18.0)
.children([
TreeTableRow::new("fe")
.cell("name", "Frontend")
.cell("headcount", 6.0),
TreeTableRow::new("be")
.cell("name", "Backend")
.cell("headcount", 12.0),
]),
TreeTableRow::new("des")
.cell("name", "Design")
.cell("headcount", 5.0),
]
}
#[test]
fn sibling_sort_preserves_hierarchy_and_tri_state_selection() {
let rows = sample_rows();
let expanded: HashSet<SharedString> = [SharedString::from("eng")].into_iter().collect();
let sort = TreeTableSort::descending("headcount");
let flat = flatten_tree_table_rows(&rows, &expanded, Some(&sort));
let ids: Vec<&str> = flat.iter().map(|v| v.row.id.as_ref()).collect();
assert_eq!(ids, vec!["eng", "be", "fe", "des"]);
let one: HashSet<SharedString> = [SharedString::from("fe")].into_iter().collect();
let (norm, mixed) = normalize_tree_table_selection(&rows, &one);
assert!(!norm.contains(&SharedString::from("eng")));
assert!(mixed.contains(&SharedString::from("eng")));
let both: HashSet<SharedString> = [SharedString::from("fe"), SharedString::from("be")]
.into_iter()
.collect();
let (norm2, mixed2) = normalize_tree_table_selection(&rows, &both);
assert!(norm2.contains(&SharedString::from("eng")));
assert!(!mixed2.contains(&SharedString::from("eng")));
}
}