Skip to main content

arc_ui/data/
tree_table.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/tree-table/tree-table.tsx` & `.module.css`
3//!
4//! P6 Component #5: `tree-table`
5//!
6//! - Nested hierarchical data table (`44px` row height, `20px` indent per depth level, vertical
7//!   ancestor guide rails, rotating chevron, `35ms`-staggered child reveal).
8//! - Sibling-only sorting: sorting reorders children inside each parent without breaking the tree.
9//! - Optional tri-state selection column: checking a parent checks all descendants, partial
10//!   descendants display the indeterminate dash state, and header checkbox selects/clears all.
11//! - Full treegrid keyboard navigation (`ArrowUp/Down/Left/Right`, `Home/End`, `Space`, `Enter`,
12//!   and `*` to expand all siblings).
13
14use std::{
15    cell::RefCell,
16    cmp::Ordering,
17    collections::{HashMap, HashSet},
18    rc::Rc,
19};
20
21use arc_motion::{
22    CubicBezier, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
23};
24use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
25use gpui_kit::{
26    AnyElement, App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
27    ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window,
28    base::StyledExt as _, canvas, div, point, prelude::*, px,
29};
30
31/// Fixed row height (`38px`, compact shadcn table row).
32pub const TREE_TABLE_ROW_HEIGHT_PX: f32 = 38.0;
33/// Indentation step per depth level (`18px`).
34pub const TREE_TABLE_INDENT_PX: f32 = 18.0;
35
36/// Column text alignment.
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
38pub enum TreeTableAlign {
39    Start,
40    End,
41}
42
43/// Sort direction for `TreeTable`.
44#[derive(Clone, Copy, Debug, Eq, PartialEq)]
45pub enum TreeTableSortDir {
46    Ascending,
47    Descending,
48}
49
50/// Active sort descriptor.
51#[derive(Clone, Debug, Eq, PartialEq)]
52pub struct TreeTableSort {
53    pub column_id: SharedString,
54    pub direction: TreeTableSortDir,
55}
56
57impl TreeTableSort {
58    pub fn ascending(column_id: impl Into<SharedString>) -> Self {
59        Self {
60            column_id: column_id.into(),
61            direction: TreeTableSortDir::Ascending,
62        }
63    }
64
65    pub fn descending(column_id: impl Into<SharedString>) -> Self {
66        Self {
67            column_id: column_id.into(),
68            direction: TreeTableSortDir::Descending,
69        }
70    }
71}
72
73/// Comparable cell value for sibling sorting.
74#[derive(Clone, Debug, PartialEq)]
75pub enum TreeTableCellValue {
76    Text(SharedString),
77    Number(f64),
78}
79
80impl TreeTableCellValue {
81    pub fn display_text(&self) -> SharedString {
82        match self {
83            Self::Text(s) => s.clone(),
84            Self::Number(n) => {
85                if (n.fract()).abs() < 1e-9 {
86                    SharedString::from(format!("{}", *n as i64))
87                } else {
88                    SharedString::from(format!("{n:.1}"))
89                }
90            }
91        }
92    }
93
94    fn cmp_value(&self, other: &Self) -> Ordering {
95        match (self, other) {
96            (Self::Number(a), Self::Number(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
97            _ => self
98                .display_text()
99                .to_lowercase()
100                .cmp(&other.display_text().to_lowercase()),
101        }
102    }
103}
104
105impl From<&str> for TreeTableCellValue {
106    fn from(s: &str) -> Self {
107        Self::Text(SharedString::from(s.to_string()))
108    }
109}
110
111impl From<String> for TreeTableCellValue {
112    fn from(s: String) -> Self {
113        Self::Text(SharedString::from(s))
114    }
115}
116
117impl From<f64> for TreeTableCellValue {
118    fn from(n: f64) -> Self {
119        Self::Number(n)
120    }
121}
122
123/// Column definition for [`TreeTable`].
124#[derive(Clone, Debug)]
125pub struct TreeTableColumn {
126    pub id: SharedString,
127    pub header: SharedString,
128    pub sortable: bool,
129    pub width: Option<f32>,
130    pub align: TreeTableAlign,
131}
132
133impl TreeTableColumn {
134    pub fn new(id: impl Into<SharedString>, header: impl Into<SharedString>) -> Self {
135        Self {
136            id: id.into(),
137            header: header.into(),
138            sortable: false,
139            width: None,
140            align: TreeTableAlign::Start,
141        }
142    }
143
144    pub fn sortable(mut self, sortable: bool) -> Self {
145        self.sortable = sortable;
146        self
147    }
148
149    pub fn width(mut self, width_px: f32) -> Self {
150        self.width = Some(width_px);
151        self
152    }
153
154    pub fn align(mut self, align: TreeTableAlign) -> Self {
155        self.align = align;
156        self
157    }
158}
159
160/// Hierarchical row entry for [`TreeTable`].
161#[derive(Clone, Debug)]
162pub struct TreeTableRow {
163    pub id: SharedString,
164    pub cells: HashMap<SharedString, TreeTableCellValue>,
165    pub children: Vec<TreeTableRow>,
166}
167
168impl TreeTableRow {
169    pub fn new(id: impl Into<SharedString>) -> Self {
170        Self {
171            id: id.into(),
172            cells: HashMap::new(),
173            children: Vec::new(),
174        }
175    }
176
177    pub fn cell(
178        mut self,
179        column_id: impl Into<SharedString>,
180        value: impl Into<TreeTableCellValue>,
181    ) -> Self {
182        self.cells.insert(column_id.into(), value.into());
183        self
184    }
185
186    pub fn children(mut self, children: impl IntoIterator<Item = TreeTableRow>) -> Self {
187        self.children = children.into_iter().collect();
188        self
189    }
190
191    pub fn has_children(&self) -> bool {
192        !self.children.is_empty()
193    }
194}
195
196/// Flattened visible row metadata computed by [`flatten_tree_table_rows`].
197#[derive(Clone, Debug)]
198pub struct VisibleTreeTableRow {
199    pub row: TreeTableRow,
200    pub depth: usize,
201    pub parent_id: Option<SharedString>,
202    pub expandable: bool,
203    pub expanded: bool,
204    pub sibling_index: usize,
205}
206
207/// Collects every expandable row ID in the hierarchy (for "Expand all").
208pub fn collect_tree_table_expandable_ids(rows: &[TreeTableRow]) -> Vec<SharedString> {
209    let mut out = Vec::new();
210    fn visit(list: &[TreeTableRow], out: &mut Vec<SharedString>) {
211        for r in list {
212            if !r.children.is_empty() {
213                out.push(r.id.clone());
214                visit(&r.children, out);
215            }
216        }
217    }
218    visit(rows, &mut out);
219    out
220}
221
222/// Sorts siblings within each parent (never breaking hierarchy) and flattens visible rows.
223pub fn flatten_tree_table_rows(
224    rows: &[TreeTableRow],
225    expanded: &HashSet<SharedString>,
226    sort: Option<&TreeTableSort>,
227) -> Vec<VisibleTreeTableRow> {
228    let mut out = Vec::new();
229    fn walk(
230        list: &[TreeTableRow],
231        depth: usize,
232        parent_id: Option<&SharedString>,
233        expanded: &HashSet<SharedString>,
234        sort: Option<&TreeTableSort>,
235        out: &mut Vec<VisibleTreeTableRow>,
236    ) {
237        let mut ordered: Vec<&TreeTableRow> = list.iter().collect();
238        if let Some(s) = sort {
239            let sign = match s.direction {
240                TreeTableSortDir::Ascending => 1i8,
241                TreeTableSortDir::Descending => -1i8,
242            };
243            ordered.sort_by(|a, b| {
244                let ord = match (a.cells.get(&s.column_id), b.cells.get(&s.column_id)) {
245                    (Some(va), Some(vb)) => va.cmp_value(vb),
246                    (Some(_), None) => Ordering::Less,
247                    (None, Some(_)) => Ordering::Greater,
248                    (None, None) => Ordering::Equal,
249                };
250                if sign > 0 { ord } else { ord.reverse() }
251            });
252        }
253        for (idx, row) in ordered.into_iter().enumerate() {
254            let expandable = !row.children.is_empty();
255            let is_open = expandable && expanded.contains(&row.id);
256            out.push(VisibleTreeTableRow {
257                row: row.clone(),
258                depth,
259                parent_id: parent_id.cloned(),
260                expandable,
261                expanded: is_open,
262                sibling_index: idx,
263            });
264            if is_open {
265                walk(&row.children, depth + 1, Some(&row.id), expanded, sort, out);
266            }
267        }
268    }
269    walk(rows, 0, None, expanded, sort, &mut out);
270    out
271}
272
273/// Normalizes tri-state parent selection: a parent becomes selected iff all its children are.
274pub fn normalize_tree_table_selection(
275    rows: &[TreeTableRow],
276    selected: &HashSet<SharedString>,
277) -> (HashSet<SharedString>, HashSet<SharedString>) {
278    let mut normalized = selected.clone();
279    let mut mixed = HashSet::new();
280
281    fn settle(
282        row: &TreeTableRow,
283        normalized: &mut HashSet<SharedString>,
284        mixed: &mut HashSet<SharedString>,
285    ) -> (bool, bool) {
286        if row.children.is_empty() {
287            let on = normalized.contains(&row.id);
288            return (on, on);
289        }
290        let mut all_on = true;
291        let mut any_on = false;
292        for kid in &row.children {
293            let (kid_all, kid_any) = settle(kid, normalized, mixed);
294            all_on &= kid_all;
295            any_on |= kid_any;
296        }
297        if all_on {
298            normalized.insert(row.id.clone());
299        } else {
300            normalized.remove(&row.id);
301            if any_on {
302                mixed.insert(row.id.clone());
303            }
304        }
305        (all_on, any_on)
306    }
307
308    for r in rows {
309        settle(r, &mut normalized, &mut mixed);
310    }
311    (normalized, mixed)
312}
313
314fn collect_subtree_ids(rows: &[TreeTableRow], target: &SharedString) -> Vec<SharedString> {
315    fn gather(row: &TreeTableRow, out: &mut Vec<SharedString>) {
316        out.push(row.id.clone());
317        for kid in &row.children {
318            gather(kid, out);
319        }
320    }
321    fn find(list: &[TreeTableRow], target: &SharedString, out: &mut Vec<SharedString>) -> bool {
322        for r in list {
323            if &r.id == target {
324                gather(r, out);
325                return true;
326            }
327            if find(&r.children, target, out) {
328                return true;
329            }
330        }
331        false
332    }
333    let mut out = Vec::new();
334    find(rows, target, &mut out);
335    out
336}
337
338fn collect_all_ids(rows: &[TreeTableRow]) -> Vec<SharedString> {
339    let mut out = Vec::new();
340    fn visit(list: &[TreeTableRow], out: &mut Vec<SharedString>) {
341        for r in list {
342            out.push(r.id.clone());
343            visit(&r.children, out);
344        }
345    }
346    visit(rows, &mut out);
347    out
348}
349
350fn paint_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
351    let rad = angle_deg.to_radians();
352    let (c, s) = (rad.cos(), rad.sin());
353    let rot = |dx: f32, dy: f32| point(px(cx + dx * c - dy * s), px(cy + dx * s + dy * c));
354    let mut pb = PathBuilder::stroke(px(1.75));
355    pb.move_to(rot(-2.0, -4.0));
356    pb.line_to(rot(2.4, 0.0));
357    pb.line_to(rot(-2.0, 4.0));
358    if let Ok(path) = pb.build() {
359        window.paint_path(path, color);
360    }
361}
362
363fn paint_sort_arrow(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
364    let rad = angle_deg.to_radians();
365    let (c, s) = (rad.cos(), rad.sin());
366    let rot = |dx: f32, dy: f32| point(px(cx + dx * c - dy * s), px(cy + dx * s + dy * c));
367    let mut shaft = PathBuilder::stroke(px(1.6));
368    shaft.move_to(rot(0.0, 4.5));
369    shaft.line_to(rot(0.0, -4.5));
370    if let Ok(p) = shaft.build() {
371        window.paint_path(p, color);
372    }
373    let mut head = PathBuilder::stroke(px(1.6));
374    head.move_to(rot(-3.2, -1.2));
375    head.line_to(rot(0.0, -4.5));
376    head.line_to(rot(3.2, -1.2));
377    if let Ok(p) = head.build() {
378        window.paint_path(p, color);
379    }
380}
381
382fn paint_tri_checkbox(cx: f32, cy: f32, checked: bool, mixed: bool, fg: Hsla, window: &mut Window) {
383    if !checked && !mixed {
384        return;
385    }
386    let mut pb = PathBuilder::stroke(px(1.8));
387    if mixed {
388        pb.move_to(point(px(cx - 4.0), px(cy)));
389        pb.line_to(point(px(cx + 4.0), px(cy)));
390    } else {
391        pb.move_to(point(px(cx - 4.2), px(cy + 0.4)));
392        pb.line_to(point(px(cx - 1.2), px(cy + 3.4)));
393        pb.line_to(point(px(cx + 4.6), px(cy - 3.2)));
394    }
395    if let Ok(path) = pb.build() {
396        window.paint_path(path, fg);
397    }
398}
399
400type IdsCallback = Rc<dyn Fn(&Vec<SharedString>, &mut Window, &mut App)>;
401type SortCallback = Rc<dyn Fn(&Option<TreeTableSort>, &mut Window, &mut App)>;
402type ActivateCallback = Rc<dyn Fn(&TreeTableRow, &mut Window, &mut App)>;
403
404#[derive(Clone)]
405struct TreeTableInternal {
406    expanded: HashSet<SharedString>,
407    selected: HashSet<SharedString>,
408    sort: Option<TreeTableSort>,
409    focused_id: Option<SharedString>,
410    hovered_id: Option<SharedString>,
411    opened_parent_id: Option<SharedString>,
412    opened_at: f64,
413    focus_handle: FocusHandle,
414}
415
416/// Nested hierarchical data table with sibling sort & tri-state checkboxes (`tree-table`).
417#[derive(IntoElement)]
418pub struct TreeTable {
419    id: ElementId,
420    label: SharedString,
421    rows: Vec<TreeTableRow>,
422    columns: Vec<TreeTableColumn>,
423    selectable: bool,
424    default_expanded: Vec<SharedString>,
425    expanded_override: Option<Vec<SharedString>>,
426    default_selected: Vec<SharedString>,
427    selected_override: Option<Vec<SharedString>>,
428    default_sort: Option<TreeTableSort>,
429    sort_override: Option<Option<TreeTableSort>>,
430    empty_message: SharedString,
431    on_expanded_change: Option<IdsCallback>,
432    on_selected_change: Option<IdsCallback>,
433    on_sort_change: Option<SortCallback>,
434    on_row_activate: Option<ActivateCallback>,
435}
436
437impl TreeTable {
438    pub fn new(
439        id: impl Into<ElementId>,
440        label: impl Into<SharedString>,
441        columns: impl IntoIterator<Item = TreeTableColumn>,
442        rows: impl IntoIterator<Item = TreeTableRow>,
443    ) -> Self {
444        Self {
445            id: id.into(),
446            label: label.into(),
447            rows: rows.into_iter().collect(),
448            columns: columns.into_iter().collect(),
449            selectable: false,
450            default_expanded: Vec::new(),
451            expanded_override: None,
452            default_selected: Vec::new(),
453            selected_override: None,
454            default_sort: None,
455            sort_override: None,
456            empty_message: SharedString::from("No rows to display"),
457            on_expanded_change: None,
458            on_selected_change: None,
459            on_sort_change: None,
460            on_row_activate: None,
461        }
462    }
463
464    pub fn selectable(mut self, selectable: bool) -> Self {
465        self.selectable = selectable;
466        self
467    }
468
469    pub fn default_expanded(
470        mut self,
471        ids: impl IntoIterator<Item = impl Into<SharedString>>,
472    ) -> Self {
473        self.default_expanded = ids.into_iter().map(Into::into).collect();
474        self
475    }
476
477    pub fn expanded(mut self, ids: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
478        self.expanded_override = Some(ids.into_iter().map(Into::into).collect());
479        self
480    }
481
482    pub fn default_selected(
483        mut self,
484        ids: impl IntoIterator<Item = impl Into<SharedString>>,
485    ) -> Self {
486        self.default_selected = ids.into_iter().map(Into::into).collect();
487        self
488    }
489
490    pub fn selected(mut self, ids: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
491        self.selected_override = Some(ids.into_iter().map(Into::into).collect());
492        self
493    }
494
495    pub fn default_sort(mut self, sort: TreeTableSort) -> Self {
496        self.default_sort = Some(sort);
497        self
498    }
499
500    pub fn sort(mut self, sort: Option<TreeTableSort>) -> Self {
501        self.sort_override = Some(sort);
502        self
503    }
504
505    pub fn empty_message(mut self, message: impl Into<SharedString>) -> Self {
506        self.empty_message = message.into();
507        self
508    }
509
510    pub fn on_expanded_change(
511        mut self,
512        cb: impl Fn(&Vec<SharedString>, &mut Window, &mut App) + 'static,
513    ) -> Self {
514        self.on_expanded_change = Some(Rc::new(cb));
515        self
516    }
517
518    pub fn on_selected_change(
519        mut self,
520        cb: impl Fn(&Vec<SharedString>, &mut Window, &mut App) + 'static,
521    ) -> Self {
522        self.on_selected_change = Some(Rc::new(cb));
523        self
524    }
525
526    pub fn on_sort_change(
527        mut self,
528        cb: impl Fn(&Option<TreeTableSort>, &mut Window, &mut App) + 'static,
529    ) -> Self {
530        self.on_sort_change = Some(Rc::new(cb));
531        self
532    }
533
534    pub fn on_row_activate(
535        mut self,
536        cb: impl Fn(&TreeTableRow, &mut Window, &mut App) + 'static,
537    ) -> Self {
538        self.on_row_activate = Some(Rc::new(cb));
539        self
540    }
541}
542
543impl RenderOnce for TreeTable {
544    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
545        let theme = cx.arc_theme().clone();
546        let colors = theme.colors;
547        let reduced = is_reduced_motion(cx);
548        let now = motion_now(cx);
549
550        let state_cell = window
551            .use_keyed_state(
552                ElementId::NamedChild(self.id.clone().into(), SharedString::from("tt-state")),
553                cx,
554                |_, cx| {
555                    Rc::new(RefCell::new(TreeTableInternal {
556                        expanded: self.default_expanded.iter().cloned().collect(),
557                        selected: self.default_selected.iter().cloned().collect(),
558                        sort: self.default_sort.clone(),
559                        focused_id: self.rows.first().map(|r| r.id.clone()),
560                        hovered_id: None,
561                        opened_parent_id: None,
562                        opened_at: now - 1.0,
563                        focus_handle: cx.focus_handle(),
564                    }))
565                },
566            )
567            .read(cx)
568            .clone();
569
570        let exp_controlled = self.expanded_override.is_some();
571        let sel_controlled = self.selected_override.is_some();
572        let sort_controlled = self.sort_override.is_some();
573
574        let (
575            expanded_set,
576            raw_selected,
577            active_sort,
578            focused_id,
579            hovered_id,
580            opened_parent,
581            opened_elapsed,
582            focus_handle,
583        ) = {
584            let mut st = state_cell.borrow_mut();
585            if let Some(ref ov) = self.expanded_override {
586                st.expanded = ov.iter().cloned().collect();
587            }
588            if let Some(ref ov) = self.selected_override {
589                st.selected = ov.iter().cloned().collect();
590            }
591            if let Some(ref ov) = self.sort_override {
592                st.sort = ov.clone();
593            }
594            let dt = (now - st.opened_at).max(0.0);
595            if !reduced && st.opened_parent_id.is_some() && dt < 0.45 {
596                window.request_animation_frame();
597            } else if dt >= 0.45 {
598                st.opened_parent_id = None;
599            }
600            (
601                st.expanded.clone(),
602                st.selected.clone(),
603                st.sort.clone(),
604                st.focused_id.clone(),
605                st.hovered_id.clone(),
606                st.opened_parent_id.clone(),
607                dt,
608                st.focus_handle.clone(),
609            )
610        };
611
612        let visible = flatten_tree_table_rows(&self.rows, &expanded_set, active_sort.as_ref());
613        let (selected_set, mixed_set) = normalize_tree_table_selection(&self.rows, &raw_selected);
614        let all_ids = collect_all_ids(&self.rows);
615        let all_checked = !all_ids.is_empty() && all_ids.iter().all(|id| selected_set.contains(id));
616        let some_checked = !all_checked && all_ids.iter().any(|id| selected_set.contains(id));
617
618        let header_bg = colors.surface_muted;
619        let row_hover_bg = oklab_mix(colors.foreground, colors.surface, 0.035);
620        let row_selected_bg = oklab_mix(colors.accent, colors.surface, 0.08);
621        let guide_color = colors.border_subtle;
622
623        // Header row
624        let mut header_row = div()
625            .w_full()
626            .h(px(36.0))
627            .px(Spacing::S3)
628            .bg(header_bg)
629            .border_b_1()
630            .border_color(colors.border)
631            .flex()
632            .flex_row()
633            .items_center()
634            .gap(Spacing::S3);
635
636        if self.selectable {
637            let st_all = state_cell.clone();
638            let rows_all = self.rows.clone();
639            let cb_sel_all = self.on_selected_change.clone();
640            let box_bg = if all_checked || some_checked {
641                colors.accent
642            } else {
643                colors.surface
644            };
645            let box_border = if all_checked || some_checked {
646                colors.accent
647            } else {
648                colors.border_strong
649            };
650            let fg_on_acc = colors.accent_foreground;
651            header_row = header_row.child(
652                div()
653                    .id(ElementId::NamedChild(
654                        self.id.clone().into(),
655                        SharedString::from("tt-select-all"),
656                    ))
657                    .w(px(28.0))
658                    .flex_none()
659                    .flex()
660                    .items_center()
661                    .justify_center()
662                    .cursor_pointer()
663                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
664                        let next_vec: Vec<SharedString> = if all_checked {
665                            Vec::new()
666                        } else {
667                            collect_all_ids(&rows_all)
668                        };
669                        if !sel_controlled {
670                            st_all.borrow_mut().selected = next_vec.iter().cloned().collect();
671                        }
672                        if let Some(ref cb) = cb_sel_all {
673                            cb(&next_vec, window, cx);
674                        }
675                        window.refresh();
676                    })
677                    .child(
678                        div()
679                            .w(px(16.0))
680                            .h(px(16.0))
681                            .rounded(px(4.0))
682                            .border_1()
683                            .border_color(box_border)
684                            .bg(box_bg)
685                            .child(
686                                canvas(
687                                    |_, _, _| {},
688                                    move |bounds, _, window, _| {
689                                        let cx_p = f32::from(bounds.origin.x)
690                                            + f32::from(bounds.size.width) * 0.5;
691                                        let cy_p = f32::from(bounds.origin.y)
692                                            + f32::from(bounds.size.height) * 0.5;
693                                        paint_tri_checkbox(
694                                            cx_p,
695                                            cy_p,
696                                            all_checked,
697                                            some_checked,
698                                            fg_on_acc,
699                                            window,
700                                        );
701                                    },
702                                )
703                                .size_full(),
704                            ),
705                    ),
706            );
707        }
708
709        for col in &self.columns {
710            let is_sorted = active_sort.as_ref().is_some_and(|s| s.column_id == col.id);
711            let is_desc = active_sort.as_ref().is_some_and(|s| {
712                s.column_id == col.id && s.direction == TreeTableSortDir::Descending
713            });
714            let arrow_angle = if reduced {
715                if is_desc { 180.0 } else { 0.0 }
716            } else {
717                arc_spring_with_options(
718                    ElementId::NamedChild(
719                        self.id.clone().into(),
720                        SharedString::from(format!("tt-sort-{}", col.id)),
721                    ),
722                    if is_desc { 180.0 } else { 0.0 },
723                    SpringOptions::new(SpringSpec::visual(0.22, 0.0))
724                        .with_initial_value(if is_desc { 180.0 } else { 0.0 }),
725                    window,
726                    cx,
727                )
728                .value
729            };
730
731            let mut cell = div()
732                .min_w(px(0.0))
733                .flex()
734                .flex_row()
735                .items_center()
736                .gap(px(5.0))
737                .text_size(Typography::TEXT_XS)
738                .font_medium()
739                .text_color(if is_sorted {
740                    colors.foreground
741                } else {
742                    colors.text_muted
743                });
744            if let Some(w) = col.width {
745                cell = cell.w(px(w)).flex_none();
746            } else {
747                cell = cell.flex_1();
748            }
749            if matches!(col.align, TreeTableAlign::End) {
750                cell = cell.justify_end();
751            }
752
753            let header_cell: AnyElement = if col.sortable {
754                let st_sort = state_cell.clone();
755                let col_id = col.id.clone();
756                let cb_sort = self.on_sort_change.clone();
757                let arrow_col = if is_sorted {
758                    colors.foreground
759                } else {
760                    colors.text_muted.opacity(0.4)
761                };
762                cell.id(ElementId::NamedChild(
763                    self.id.clone().into(),
764                    SharedString::from(format!("tt-col-{}", col.id)),
765                ))
766                .cursor_pointer()
767                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
768                    let next = {
769                        let cur = st_sort.borrow().sort.clone();
770                        match cur {
771                            Some(ref s) if s.column_id == col_id => match s.direction {
772                                TreeTableSortDir::Ascending => {
773                                    Some(TreeTableSort::descending(col_id.clone()))
774                                }
775                                TreeTableSortDir::Descending => None,
776                            },
777                            _ => Some(TreeTableSort::ascending(col_id.clone())),
778                        }
779                    };
780                    if !sort_controlled {
781                        st_sort.borrow_mut().sort = next.clone();
782                    }
783                    if let Some(ref cb) = cb_sort {
784                        cb(&next, window, cx);
785                    }
786                    window.refresh();
787                })
788                .child(col.header.clone())
789                .child(
790                    div().w(px(14.0)).h(px(14.0)).flex_none().child(
791                        canvas(
792                            |_, _, _| {},
793                            move |bounds, _, window, _| {
794                                let cx_p =
795                                    f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
796                                let cy_p = f32::from(bounds.origin.y)
797                                    + f32::from(bounds.size.height) * 0.5;
798                                paint_sort_arrow(cx_p, cy_p, arrow_angle, arrow_col, window);
799                            },
800                        )
801                        .size_full(),
802                    ),
803                )
804                .into_any_element()
805            } else {
806                cell.child(col.header.clone()).into_any_element()
807            };
808
809            header_row = header_row.child(header_cell);
810        }
811
812        // Body rows
813        let mut body = div().w_full().flex().flex_col();
814        if visible.is_empty() {
815            body = body.child(
816                div()
817                    .w_full()
818                    .py(Spacing::S8)
819                    .text_center()
820                    .text_size(Typography::TEXT_SM)
821                    .text_color(colors.text_muted)
822                    .child(self.empty_message.clone()),
823            );
824        } else {
825            for item in &visible {
826                let row_id = item.row.id.clone();
827                let is_selected = selected_set.contains(&row_id);
828                let is_mixed = mixed_set.contains(&row_id);
829                let is_hovered = hovered_id.as_ref() == Some(&row_id);
830                let is_focused = focused_id.as_ref() == Some(&row_id);
831
832                // Stagger newly opened children
833                let reveal_alpha = if !reduced
834                    && opened_parent.as_ref() == item.parent_id.as_ref()
835                    && item.parent_id.is_some()
836                {
837                    let delay = (item.sibling_index.min(7) as f64) * 0.035;
838                    let local = (opened_elapsed - delay).max(0.0);
839                    let t = (local / 0.22).clamp(0.0, 1.0) as f32;
840                    CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
841                } else {
842                    1.0
843                };
844
845                let row_bg = if is_selected {
846                    row_selected_bg
847                } else if is_hovered {
848                    row_hover_bg
849                } else {
850                    colors.surface
851                };
852
853                let chevron_angle = if reduced {
854                    if item.expanded { 90.0 } else { 0.0 }
855                } else {
856                    arc_spring_with_options(
857                        ElementId::NamedChild(
858                            self.id.clone().into(),
859                            SharedString::from(format!("tt-chev-{row_id}")),
860                        ),
861                        if item.expanded { 90.0 } else { 0.0 },
862                        SpringOptions::new(SpringSpec::visual(0.22, 0.0))
863                            .with_initial_value(if item.expanded { 90.0 } else { 0.0 }),
864                        window,
865                        cx,
866                    )
867                    .value
868                };
869
870                let st_hover = state_cell.clone();
871                let rid_hover = row_id.clone();
872                let st_click = state_cell.clone();
873                let row_click = item.row.clone();
874                let expandable_click = item.expandable;
875                let cb_exp_click = self.on_expanded_change.clone();
876                let cb_act_click = self.on_row_activate.clone();
877                let fh_click = focus_handle.clone();
878
879                let mut row_el = div()
880                    .id(ElementId::NamedChild(
881                        self.id.clone().into(),
882                        SharedString::from(format!("tt-row-{row_id}")),
883                    ))
884                    .role(Role::Row)
885                    .w_full()
886                    .min_h(px(TREE_TABLE_ROW_HEIGHT_PX))
887                    .px(Spacing::S3)
888                    .bg(row_bg)
889                    .border_b_1()
890                    .border_color(colors.border_subtle)
891                    .opacity(reveal_alpha)
892                    .flex()
893                    .flex_row()
894                    .items_center()
895                    .gap(Spacing::S3)
896                    .cursor_pointer()
897                    .when(is_focused, |el| el.border_l_2().border_color(colors.accent))
898                    .on_hover(move |hovered, window, _| {
899                        let mut st = st_hover.borrow_mut();
900                        if *hovered {
901                            st.hovered_id = Some(rid_hover.clone());
902                        } else if st.hovered_id.as_ref() == Some(&rid_hover) {
903                            st.hovered_id = None;
904                        }
905                        window.refresh();
906                    })
907                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
908                        fh_click.focus(window, cx);
909                        st_click.borrow_mut().focused_id = Some(row_click.id.clone());
910                        if expandable_click {
911                            let next_vec: Vec<SharedString> = {
912                                let mut st = st_click.borrow_mut();
913                                if st.expanded.contains(&row_click.id) {
914                                    st.expanded.remove(&row_click.id);
915                                } else {
916                                    st.expanded.insert(row_click.id.clone());
917                                    st.opened_parent_id = Some(row_click.id.clone());
918                                    st.opened_at = motion_now(cx);
919                                }
920                                st.expanded.iter().cloned().collect()
921                            };
922                            if exp_controlled {
923                                // Restore until parent updates controlled prop
924                            }
925                            if let Some(ref cb) = cb_exp_click {
926                                cb(&next_vec, window, cx);
927                            }
928                        } else if let Some(ref cb) = cb_act_click {
929                            cb(&row_click, window, cx);
930                        }
931                        window.refresh();
932                    });
933
934                if self.selectable {
935                    let st_chk = state_cell.clone();
936                    let rid_chk = row_id.clone();
937                    let rows_chk = self.rows.clone();
938                    let cb_sel = self.on_selected_change.clone();
939                    let box_bg = if is_selected || is_mixed {
940                        colors.accent
941                    } else {
942                        colors.surface
943                    };
944                    let box_border = if is_selected || is_mixed {
945                        colors.accent
946                    } else {
947                        colors.border_strong
948                    };
949                    let fg_on_acc = colors.accent_foreground;
950                    row_el = row_el.child(
951                        div()
952                            .id(ElementId::NamedChild(
953                                self.id.clone().into(),
954                                SharedString::from(format!("tt-chk-{row_id}")),
955                            ))
956                            .w(px(28.0))
957                            .flex_none()
958                            .flex()
959                            .items_center()
960                            .justify_center()
961                            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
962                                cx.stop_propagation();
963                                let sub = collect_subtree_ids(&rows_chk, &rid_chk);
964                                let next_set = {
965                                    let mut cur = st_chk.borrow().selected.clone();
966                                    let turn_on = !is_selected;
967                                    for id in sub {
968                                        if turn_on {
969                                            cur.insert(id);
970                                        } else {
971                                            cur.remove(&id);
972                                        }
973                                    }
974                                    normalize_tree_table_selection(&rows_chk, &cur).0
975                                };
976                                let next_vec: Vec<SharedString> =
977                                    next_set.iter().cloned().collect();
978                                if !sel_controlled {
979                                    st_chk.borrow_mut().selected = next_set;
980                                }
981                                if let Some(ref cb) = cb_sel {
982                                    cb(&next_vec, window, cx);
983                                }
984                                window.refresh();
985                            })
986                            .child(
987                                div()
988                                    .w(px(16.0))
989                                    .h(px(16.0))
990                                    .rounded(px(4.0))
991                                    .border_1()
992                                    .border_color(box_border)
993                                    .bg(box_bg)
994                                    .child(
995                                        canvas(
996                                            |_, _, _| {},
997                                            move |bounds, _, window, _| {
998                                                let cx_p = f32::from(bounds.origin.x)
999                                                    + f32::from(bounds.size.width) * 0.5;
1000                                                let cy_p = f32::from(bounds.origin.y)
1001                                                    + f32::from(bounds.size.height) * 0.5;
1002                                                paint_tri_checkbox(
1003                                                    cx_p,
1004                                                    cy_p,
1005                                                    is_selected,
1006                                                    is_mixed,
1007                                                    fg_on_acc,
1008                                                    window,
1009                                                );
1010                                            },
1011                                        )
1012                                        .size_full(),
1013                                    ),
1014                            ),
1015                    );
1016                }
1017
1018                for (col_idx, col) in self.columns.iter().enumerate() {
1019                    let text = item
1020                        .row
1021                        .cells
1022                        .get(&col.id)
1023                        .map(TreeTableCellValue::display_text)
1024                        .unwrap_or_default();
1025
1026                    let mut cell = div()
1027                        .min_w(px(0.0))
1028                        .flex()
1029                        .flex_row()
1030                        .items_center()
1031                        .text_size(Typography::TEXT_SM)
1032                        .text_color(if col_idx == 0 {
1033                            colors.foreground
1034                        } else {
1035                            colors.text_secondary
1036                        });
1037
1038                    if let Some(w) = col.width {
1039                        cell = cell.w(px(w)).flex_none();
1040                    } else {
1041                        cell = cell.flex_1();
1042                    }
1043                    if matches!(col.align, TreeTableAlign::End) {
1044                        cell = cell.justify_end();
1045                    }
1046
1047                    if col_idx == 0 {
1048                        // Tree indentation + ancestor guide lines + chevron
1049                        let mut tree_prefix = div()
1050                            .relative()
1051                            .flex()
1052                            .flex_row()
1053                            .items_center()
1054                            .h(px(TREE_TABLE_ROW_HEIGHT_PX))
1055                            .pl(px(item.depth as f32 * TREE_TABLE_INDENT_PX));
1056
1057                        for level in 0..item.depth {
1058                            tree_prefix = tree_prefix.child(
1059                                div()
1060                                    .absolute()
1061                                    .left(px(level as f32 * TREE_TABLE_INDENT_PX + 11.0))
1062                                    .top_0()
1063                                    .bottom_0()
1064                                    .w(px(1.0))
1065                                    .bg(guide_color),
1066                            );
1067                        }
1068
1069                        let chev_col = colors.text_muted;
1070                        let chevron_box: AnyElement = if item.expandable {
1071                            div()
1072                                .w(px(22.0))
1073                                .h(px(22.0))
1074                                .mr(px(4.0))
1075                                .flex_none()
1076                                .child(
1077                                    canvas(
1078                                        |_, _, _| {},
1079                                        move |bounds, _, window, _| {
1080                                            let cx_p = f32::from(bounds.origin.x)
1081                                                + f32::from(bounds.size.width) * 0.5;
1082                                            let cy_p = f32::from(bounds.origin.y)
1083                                                + f32::from(bounds.size.height) * 0.5;
1084                                            paint_chevron(
1085                                                cx_p,
1086                                                cy_p,
1087                                                chevron_angle,
1088                                                chev_col,
1089                                                window,
1090                                            );
1091                                        },
1092                                    )
1093                                    .size_full(),
1094                                )
1095                                .into_any_element()
1096                        } else {
1097                            div().w(px(22.0)).mr(px(4.0)).flex_none().into_any_element()
1098                        };
1099
1100                        cell = cell.child(tree_prefix.child(chevron_box)).child(
1101                            div()
1102                                .flex_1()
1103                                .min_w(px(0.0))
1104                                .truncate()
1105                                .when(item.expandable, |el| el.font_medium())
1106                                .child(text),
1107                        );
1108                    } else {
1109                        cell = cell.child(div().truncate().child(text));
1110                    }
1111
1112                    row_el = row_el.child(cell);
1113                }
1114
1115                body = body.child(row_el);
1116            }
1117        }
1118
1119        // Keyboard treegrid handler
1120        let st_key = state_cell.clone();
1121        let vis_key = visible.clone();
1122        let rows_key = self.rows.clone();
1123        let cb_exp_key = self.on_expanded_change.clone();
1124        let cb_sel_key = self.on_selected_change.clone();
1125        let cb_act_key = self.on_row_activate.clone();
1126        let selectable_key = self.selectable;
1127
1128        div()
1129            .id(self.id)
1130            .role(Role::Grid)
1131            .aria_label(self.label)
1132            .track_focus(&focus_handle)
1133            .w_full()
1134            .rounded(Radii::PANEL)
1135            .border_1()
1136            .border_color(colors.border)
1137            .bg(colors.surface)
1138            .overflow_hidden()
1139            .on_key_down(move |ev: &KeyDownEvent, window, cx| {
1140                if vis_key.is_empty() {
1141                    return;
1142                }
1143                let cur_idx = {
1144                    let st = st_key.borrow();
1145                    st.focused_id
1146                        .as_ref()
1147                        .and_then(|id| vis_key.iter().position(|v| &v.row.id == id))
1148                        .unwrap_or(0)
1149                };
1150                let cur = &vis_key[cur_idx];
1151                match ev.keystroke.key.as_str() {
1152                    "down" => {
1153                        let next = (cur_idx + 1).min(vis_key.len() - 1);
1154                        st_key.borrow_mut().focused_id = Some(vis_key[next].row.id.clone());
1155                        window.refresh();
1156                    }
1157                    "up" => {
1158                        let next = cur_idx.saturating_sub(1);
1159                        st_key.borrow_mut().focused_id = Some(vis_key[next].row.id.clone());
1160                        window.refresh();
1161                    }
1162                    "home" => {
1163                        st_key.borrow_mut().focused_id = Some(vis_key[0].row.id.clone());
1164                        window.refresh();
1165                    }
1166                    "end" => {
1167                        st_key.borrow_mut().focused_id =
1168                            Some(vis_key[vis_key.len() - 1].row.id.clone());
1169                        window.refresh();
1170                    }
1171                    "right" => {
1172                        if cur.expandable && !cur.expanded {
1173                            let next_vec = {
1174                                let mut st = st_key.borrow_mut();
1175                                st.expanded.insert(cur.row.id.clone());
1176                                st.opened_parent_id = Some(cur.row.id.clone());
1177                                st.opened_at = motion_now(cx);
1178                                st.expanded.iter().cloned().collect::<Vec<_>>()
1179                            };
1180                            if let Some(ref cb) = cb_exp_key {
1181                                cb(&next_vec, window, cx);
1182                            }
1183                            window.refresh();
1184                        } else if cur.expanded && cur_idx + 1 < vis_key.len() {
1185                            st_key.borrow_mut().focused_id =
1186                                Some(vis_key[cur_idx + 1].row.id.clone());
1187                            window.refresh();
1188                        }
1189                    }
1190                    "left" => {
1191                        if cur.expandable && cur.expanded {
1192                            let next_vec = {
1193                                let mut st = st_key.borrow_mut();
1194                                st.expanded.remove(&cur.row.id);
1195                                st.expanded.iter().cloned().collect::<Vec<_>>()
1196                            };
1197                            if let Some(ref cb) = cb_exp_key {
1198                                cb(&next_vec, window, cx);
1199                            }
1200                            window.refresh();
1201                        } else if let Some(ref pid) = cur.parent_id {
1202                            st_key.borrow_mut().focused_id = Some(pid.clone());
1203                            window.refresh();
1204                        }
1205                    }
1206                    "space" if selectable_key => {
1207                        let sub = collect_subtree_ids(&rows_key, &cur.row.id);
1208                        let next_set = {
1209                            let mut cur_sel = st_key.borrow().selected.clone();
1210                            let on = !cur_sel.contains(&cur.row.id);
1211                            for id in sub {
1212                                if on {
1213                                    cur_sel.insert(id);
1214                                } else {
1215                                    cur_sel.remove(&id);
1216                                }
1217                            }
1218                            normalize_tree_table_selection(&rows_key, &cur_sel).0
1219                        };
1220                        let next_vec: Vec<SharedString> = next_set.iter().cloned().collect();
1221                        if !sel_controlled {
1222                            st_key.borrow_mut().selected = next_set;
1223                        }
1224                        if let Some(ref cb) = cb_sel_key {
1225                            cb(&next_vec, window, cx);
1226                        }
1227                        window.refresh();
1228                    }
1229                    "enter" => {
1230                        if cur.expandable {
1231                            let next_vec = {
1232                                let mut st = st_key.borrow_mut();
1233                                if st.expanded.contains(&cur.row.id) {
1234                                    st.expanded.remove(&cur.row.id);
1235                                } else {
1236                                    st.expanded.insert(cur.row.id.clone());
1237                                    st.opened_parent_id = Some(cur.row.id.clone());
1238                                    st.opened_at = motion_now(cx);
1239                                }
1240                                st.expanded.iter().cloned().collect::<Vec<_>>()
1241                            };
1242                            if let Some(ref cb) = cb_exp_key {
1243                                cb(&next_vec, window, cx);
1244                            }
1245                        } else if let Some(ref cb) = cb_act_key {
1246                            cb(&cur.row, window, cx);
1247                        }
1248                        window.refresh();
1249                    }
1250                    "*" => {
1251                        let siblings: Vec<SharedString> = vis_key
1252                            .iter()
1253                            .filter(|v| v.parent_id == cur.parent_id && v.expandable)
1254                            .map(|v| v.row.id.clone())
1255                            .collect();
1256                        let next_vec = {
1257                            let mut st = st_key.borrow_mut();
1258                            for sid in siblings {
1259                                st.expanded.insert(sid);
1260                            }
1261                            st.expanded.iter().cloned().collect::<Vec<_>>()
1262                        };
1263                        if let Some(ref cb) = cb_exp_key {
1264                            cb(&next_vec, window, cx);
1265                        }
1266                        window.refresh();
1267                    }
1268                    _ => {}
1269                }
1270            })
1271            .child(header_row)
1272            .child(body)
1273            .into_any_element()
1274    }
1275}
1276
1277#[cfg(test)]
1278mod tests {
1279    use super::*;
1280
1281    fn sample_rows() -> Vec<TreeTableRow> {
1282        vec![
1283            TreeTableRow::new("eng")
1284                .cell("name", "Engineering")
1285                .cell("headcount", 18.0)
1286                .children([
1287                    TreeTableRow::new("fe")
1288                        .cell("name", "Frontend")
1289                        .cell("headcount", 6.0),
1290                    TreeTableRow::new("be")
1291                        .cell("name", "Backend")
1292                        .cell("headcount", 12.0),
1293                ]),
1294            TreeTableRow::new("des")
1295                .cell("name", "Design")
1296                .cell("headcount", 5.0),
1297        ]
1298    }
1299
1300    #[test]
1301    fn sibling_sort_preserves_hierarchy_and_tri_state_selection() {
1302        let rows = sample_rows();
1303        let expanded: HashSet<SharedString> = [SharedString::from("eng")].into_iter().collect();
1304        let sort = TreeTableSort::descending("headcount");
1305        let flat = flatten_tree_table_rows(&rows, &expanded, Some(&sort));
1306        let ids: Vec<&str> = flat.iter().map(|v| v.row.id.as_ref()).collect();
1307        // Engineering (18) stays above Design (5); inside Engineering, Backend (12) precedes Frontend (6).
1308        assert_eq!(ids, vec!["eng", "be", "fe", "des"]);
1309
1310        // Selecting one child makes parent mixed, not selected.
1311        let one: HashSet<SharedString> = [SharedString::from("fe")].into_iter().collect();
1312        let (norm, mixed) = normalize_tree_table_selection(&rows, &one);
1313        assert!(!norm.contains(&SharedString::from("eng")));
1314        assert!(mixed.contains(&SharedString::from("eng")));
1315
1316        // Selecting both children promotes parent to fully selected.
1317        let both: HashSet<SharedString> = [SharedString::from("fe"), SharedString::from("be")]
1318            .into_iter()
1319            .collect();
1320        let (norm2, mixed2) = normalize_tree_table_selection(&rows, &both);
1321        assert!(norm2.contains(&SharedString::from("eng")));
1322        assert!(!mixed2.contains(&SharedString::from("eng")));
1323    }
1324}