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::{
App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window,
base::StyledExt as _, canvas, div, point, prelude::*, px,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SortDirection {
Asc,
Desc,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SortState {
pub key: SharedString,
pub direction: SortDirection,
}
impl SortState {
pub fn asc(key: impl Into<SharedString>) -> Self {
Self {
key: key.into(),
direction: SortDirection::Asc,
}
}
pub fn desc(key: impl Into<SharedString>) -> Self {
Self {
key: key.into(),
direction: SortDirection::Desc,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum DataCellValue {
Text(SharedString),
Number(f64),
FormattedNumber { value: f64, display: SharedString },
Empty,
}
impl DataCellValue {
pub fn is_empty(&self) -> bool {
match self {
Self::Empty => true,
Self::Text(s) => s.trim().is_empty(),
Self::Number(_) | Self::FormattedNumber { .. } => false,
}
}
pub fn display_text(&self) -> SharedString {
match self {
Self::Empty => SharedString::from("—"),
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}"))
}
}
Self::FormattedNumber { display, .. } => display.clone(),
}
}
fn compare_non_empty(&self, other: &Self) -> Ordering {
match (self, other) {
(
Self::Number(a) | Self::FormattedNumber { value: a, .. },
Self::Number(b) | Self::FormattedNumber { value: b, .. },
) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
_ => self
.display_text()
.to_lowercase()
.cmp(&other.display_text().to_lowercase()),
}
}
}
impl From<&str> for DataCellValue {
fn from(s: &str) -> Self {
if s.is_empty() {
Self::Empty
} else {
Self::Text(SharedString::from(s.to_string()))
}
}
}
impl From<String> for DataCellValue {
fn from(s: String) -> Self {
if s.is_empty() {
Self::Empty
} else {
Self::Text(SharedString::from(s))
}
}
}
impl From<f64> for DataCellValue {
fn from(n: f64) -> Self {
Self::Number(n)
}
}
#[derive(Clone, Debug)]
pub struct DataColumn {
pub key: SharedString,
pub label: SharedString,
pub sortable: bool,
pub numeric: bool,
pub width: Option<f32>,
}
impl DataColumn {
pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
key: key.into(),
label: label.into(),
sortable: true,
numeric: false,
width: None,
}
}
pub fn sortable(mut self, sortable: bool) -> Self {
self.sortable = sortable;
self
}
pub fn numeric(mut self, numeric: bool) -> Self {
self.numeric = numeric;
self
}
pub fn width(mut self, width_px: f32) -> Self {
self.width = Some(width_px);
self
}
}
#[derive(Clone, Debug)]
pub struct DataTableRow {
pub key: SharedString,
pub cells: HashMap<SharedString, DataCellValue>,
}
impl DataTableRow {
pub fn new(key: impl Into<SharedString>) -> Self {
Self {
key: key.into(),
cells: HashMap::new(),
}
}
pub fn cell(
mut self,
col_key: impl Into<SharedString>,
value: impl Into<DataCellValue>,
) -> Self {
self.cells.insert(col_key.into(), value.into());
self
}
}
pub fn sort_data_table_rows(rows: &[DataTableRow], sort: Option<&SortState>) -> Vec<DataTableRow> {
let Some(sort) = sort else {
return rows.to_vec();
};
let mut indexed: Vec<(usize, &DataTableRow)> = rows.iter().enumerate().collect();
indexed.sort_by(|(ia, a), (ib, b)| {
let va = a.cells.get(&sort.key).unwrap_or(&DataCellValue::Empty);
let vb = b.cells.get(&sort.key).unwrap_or(&DataCellValue::Empty);
let ea = va.is_empty();
let eb = vb.is_empty();
if ea || eb {
return match (ea, eb) {
(true, true) => ia.cmp(ib),
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => unreachable!(),
};
}
let ord = va.compare_non_empty(vb);
let directed = match sort.direction {
SortDirection::Asc => ord,
SortDirection::Desc => ord.reverse(),
};
directed.then_with(|| ia.cmp(ib))
});
indexed.into_iter().map(|(_, r)| r.clone()).collect()
}
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_checkbox_mark(
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 SortChangeCallback = Rc<dyn Fn(&SortState, &mut Window, &mut App)>;
type SelectionChangeCallback = Rc<dyn Fn(&Vec<SharedString>, &mut Window, &mut App)>;
#[derive(Clone)]
struct SortableTableInternal {
sort: Option<SortState>,
selected: HashSet<SharedString>,
anchor_key: Option<SharedString>,
hovered_key: Option<SharedString>,
last_count: usize,
count_dir: i8,
count_changed_at: f64,
focus_handle: FocusHandle,
}
#[derive(IntoElement)]
pub struct SortableDataTable {
id: ElementId,
caption: SharedString,
columns: Vec<DataColumn>,
rows: Vec<DataTableRow>,
empty_message: SharedString,
default_sort: Option<SortState>,
selectable: bool,
selected_override: Option<Vec<SharedString>>,
default_selected: Vec<SharedString>,
item_singular: SharedString,
item_plural: SharedString,
on_sort_change: Option<SortChangeCallback>,
on_selection_change: Option<SelectionChangeCallback>,
}
impl SortableDataTable {
pub fn new(
id: impl Into<ElementId>,
columns: impl IntoIterator<Item = DataColumn>,
rows: impl IntoIterator<Item = DataTableRow>,
) -> Self {
Self {
id: id.into(),
caption: SharedString::from("Data table"),
columns: columns.into_iter().collect(),
rows: rows.into_iter().collect(),
empty_message: SharedString::from("No rows to show"),
default_sort: None,
selectable: false,
selected_override: None,
default_selected: Vec::new(),
item_singular: SharedString::from("row"),
item_plural: SharedString::from("rows"),
on_sort_change: None,
on_selection_change: None,
}
}
pub fn caption(mut self, caption: impl Into<SharedString>) -> Self {
self.caption = caption.into();
self
}
pub fn empty_message(mut self, message: impl Into<SharedString>) -> Self {
self.empty_message = message.into();
self
}
pub fn default_sort(mut self, sort: SortState) -> Self {
self.default_sort = Some(sort);
self
}
pub fn selectable(mut self, selectable: bool) -> Self {
self.selectable = selectable;
self
}
pub fn default_selected(
mut self,
keys: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.default_selected = keys.into_iter().map(Into::into).collect();
self
}
pub fn selected(mut self, keys: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
self.selected_override = Some(keys.into_iter().map(Into::into).collect());
self
}
pub fn item_name(
mut self,
singular: impl Into<SharedString>,
plural: impl Into<SharedString>,
) -> Self {
self.item_singular = singular.into();
self.item_plural = plural.into();
self
}
pub fn on_sort_change(
mut self,
cb: impl Fn(&SortState, &mut Window, &mut App) + 'static,
) -> Self {
self.on_sort_change = Some(Rc::new(cb));
self
}
pub fn on_selection_change(
mut self,
cb: impl Fn(&Vec<SharedString>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_selection_change = Some(Rc::new(cb));
self
}
}
impl RenderOnce for SortableDataTable {
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("sdt-state")),
cx,
|_, cx| {
Rc::new(RefCell::new(SortableTableInternal {
sort: self.default_sort.clone(),
selected: self.default_selected.iter().cloned().collect(),
anchor_key: None,
hovered_key: None,
last_count: self.rows.len(),
count_dir: 1,
count_changed_at: now - 1.0,
focus_handle: cx.focus_handle(),
}))
},
)
.read(cx)
.clone();
let sel_controlled = self.selected_override.is_some();
let (active_sort, selected_set, hovered_key, focus_handle) = {
let mut st = state_cell.borrow_mut();
if let Some(ref ov) = self.selected_override {
st.selected = ov.iter().cloned().collect();
}
(
st.sort.clone(),
st.selected.clone(),
st.hovered_key.clone(),
st.focus_handle.clone(),
)
};
let sorted_rows = sort_data_table_rows(&self.rows, active_sort.as_ref());
let ordered_keys: Vec<SharedString> = sorted_rows.iter().map(|r| r.key.clone()).collect();
let selected_count = ordered_keys
.iter()
.filter(|k| selected_set.contains(*k))
.count();
let all_selected = !ordered_keys.is_empty() && selected_count == ordered_keys.len();
let some_selected = selected_count > 0 && !all_selected;
let shown_count = if selected_count > 0 {
selected_count
} else {
ordered_keys.len()
};
let (count_dir, count_elapsed) = {
let mut st = state_cell.borrow_mut();
if st.last_count != shown_count {
st.count_dir = if shown_count > st.last_count { 1 } else { -1 };
st.last_count = shown_count;
st.count_changed_at = now;
}
let dt = (now - st.count_changed_at).max(0.0);
if !reduced && dt < 0.26 {
window.request_animation_frame();
}
(st.count_dir, dt)
};
let sorted_col_tint = oklab_mix(colors.foreground, colors.surface, 0.028);
let row_hover_bg = oklab_mix(colors.foreground, colors.surface, 0.04);
let row_selected_bg = oklab_mix(colors.accent, colors.surface, 0.08);
let mut header = div()
.w_full()
.h(px(36.0))
.px(Spacing::S3)
.bg(colors.surface_muted)
.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 keys_all = ordered_keys.clone();
let cb_sel = self.on_selection_change.clone();
let box_bg = if all_selected || some_selected {
colors.accent
} else {
colors.surface
};
let box_border = if all_selected || some_selected {
colors.accent
} else {
colors.border_strong
};
let fg_acc = colors.accent_foreground;
header = header.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from("sdt-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 = if all_selected {
Vec::new()
} else {
keys_all.clone()
};
if !sel_controlled {
st_all.borrow_mut().selected = next_vec.iter().cloned().collect();
}
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_checkbox_mark(
cx_p,
cy_p,
all_selected,
some_selected,
fg_acc,
window,
);
},
)
.size_full(),
),
),
);
}
for col in &self.columns {
let is_sorted = active_sort.as_ref().is_some_and(|s| s.key == col.key);
let is_desc = active_sort
.as_ref()
.is_some_and(|s| s.key == col.key && s.direction == SortDirection::Desc);
let target_angle = if is_desc { 180.0 } else { 0.0 };
let angle = if reduced {
target_angle
} else {
arc_spring_with_options(
ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("sdt-arrow-{}", col.key)),
),
target_angle,
SpringOptions::new(SpringSpec::visual(0.20, 0.0))
.with_initial_value(target_angle),
window,
cx,
)
.value
};
let mut th = div()
.min_w(px(0.0))
.h_full()
.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 {
th = th.w(px(w)).flex_none();
} else {
th = th.flex_1();
}
if col.numeric {
th = th.justify_end();
}
let header_cell: gpui_kit::AnyElement = if col.sortable {
let st_sort = state_cell.clone();
let col_key = col.key.clone();
let cb_sort = self.on_sort_change.clone();
let arrow_col = if is_sorted {
colors.foreground
} else {
colors.text_muted.opacity(0.35)
};
th.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("sdt-th-{}", col.key)),
))
.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.key == col_key && s.direction == SortDirection::Asc =>
{
SortState::desc(col_key.clone())
}
_ => SortState::asc(col_key.clone()),
}
};
st_sort.borrow_mut().sort = Some(next.clone());
if let Some(ref cb) = cb_sort {
cb(&next, window, cx);
}
window.refresh();
})
.child(col.label.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, angle, arrow_col, window);
},
)
.size_full(),
),
)
.into_any_element()
} else {
th.child(col.label.clone()).into_any_element()
};
header = header.child(header_cell);
}
let mut body = div().w_full().flex().flex_col();
if sorted_rows.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 row in &sorted_rows {
let row_key = row.key.clone();
let is_selected = selected_set.contains(&row_key);
let is_hovered = hovered_key.as_ref() == Some(&row_key);
let row_bg = if is_selected {
row_selected_bg
} else if is_hovered {
row_hover_bg
} else {
colors.surface
};
let st_hover = state_cell.clone();
let rk_hover = row_key.clone();
let st_click = state_cell.clone();
let rk_click = row_key.clone();
let keys_click = ordered_keys.clone();
let cb_sel_row = self.on_selection_change.clone();
let selectable_row = self.selectable;
let fh_row = focus_handle.clone();
let mut row_el = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("sdt-row-{row_key}")),
))
.role(Role::Row)
.w_full()
.min_h(px(38.0))
.px(Spacing::S3)
.bg(row_bg)
.border_b_1()
.border_color(colors.border_subtle)
.flex()
.flex_row()
.items_center()
.gap(Spacing::S3)
.when(selectable_row, |el| el.cursor_pointer())
.on_hover(move |hovered, window, _| {
let mut st = st_hover.borrow_mut();
if *hovered {
st.hovered_key = Some(rk_hover.clone());
} else if st.hovered_key.as_ref() == Some(&rk_hover) {
st.hovered_key = None;
}
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
if !selectable_row {
return;
}
fh_row.focus(window, cx);
let next_vec: Vec<SharedString> = {
let mut st = st_click.borrow_mut();
let turn_on = !st.selected.contains(&rk_click);
let range_keys: Vec<SharedString> = if ev.modifiers.shift {
if let (Some(anchor), Some(to)) = (
st.anchor_key
.as_ref()
.and_then(|a| keys_click.iter().position(|k| k == a)),
keys_click.iter().position(|k| k == &rk_click),
) {
let (lo, hi) = if anchor <= to {
(anchor, to)
} else {
(to, anchor)
};
keys_click[lo..=hi].to_vec()
} else {
vec![rk_click.clone()]
}
} else {
vec![rk_click.clone()]
};
for k in range_keys {
if turn_on {
st.selected.insert(k);
} else {
st.selected.remove(&k);
}
}
st.anchor_key = Some(rk_click.clone());
keys_click
.iter()
.filter(|k| st.selected.contains(*k))
.cloned()
.collect()
};
if let Some(ref cb) = cb_sel_row {
cb(&next_vec, window, cx);
}
window.refresh();
});
if self.selectable {
let box_bg = if is_selected {
colors.accent
} else {
colors.surface
};
let box_border = if is_selected {
colors.accent
} else {
colors.border_strong
};
let fg_acc = colors.accent_foreground;
row_el = row_el.child(
div()
.w(px(28.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.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_checkbox_mark(
cx_p,
cy_p,
is_selected,
false,
fg_acc,
window,
);
},
)
.size_full(),
),
),
);
}
for (col_idx, col) in self.columns.iter().enumerate() {
let is_sorted_col = active_sort.as_ref().is_some_and(|s| s.key == col.key);
let cell_val = row.cells.get(&col.key).unwrap_or(&DataCellValue::Empty);
let mut td = div()
.min_w(px(0.0))
.h(px(38.0))
.px(px(2.0))
.flex()
.flex_row()
.items_center()
.text_size(Typography::TEXT_SM)
.text_color(if cell_val.is_empty() {
colors.text_muted
} else if col_idx == 0 {
colors.foreground
} else {
colors.text_secondary
});
if is_sorted_col && !is_selected && !is_hovered {
td = td.bg(sorted_col_tint);
}
if let Some(w) = col.width {
td = td.w(px(w)).flex_none();
} else {
td = td.flex_1();
}
if col.numeric {
td = td.justify_end();
}
if col_idx == 0 {
td = td.font_medium();
}
row_el =
row_el.child(td.child(div().truncate().child(cell_val.display_text())));
}
body = body.child(row_el);
}
}
let count_t = if reduced {
1.0
} else {
CubicBezier::new(0.16, 1.0, 0.3, 1.0)
.sample((count_elapsed / 0.24).clamp(0.0, 1.0) as f32)
};
let count_y = (1.0 - count_t) * 5.0 * count_dir as f32;
let noun = if selected_count > 0 {
SharedString::from("selected")
} else if ordered_keys.len() == 1 {
self.item_singular.clone()
} else {
self.item_plural.clone()
};
let st_clear = state_cell.clone();
let cb_sel_clear = self.on_selection_change.clone();
let footer = div()
.w_full()
.px(Spacing::S3)
.py(Spacing::S2)
.bg(colors.surface_muted)
.flex()
.flex_row()
.items_center()
.justify_between()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(5.0))
.child(
div()
.relative()
.top(px(count_y))
.opacity(count_t)
.font_medium()
.text_color(colors.foreground)
.child(format!("{shown_count}")),
)
.child(noun),
)
.when(selected_count > 0, |el| {
el.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from("sdt-clear"),
))
.px(Spacing::S2)
.py(px(2.0))
.rounded(Radii::CONTROL)
.text_color(colors.foreground)
.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let empty = Vec::new();
if !sel_controlled {
st_clear.borrow_mut().selected.clear();
}
if let Some(ref cb) = cb_sel_clear {
cb(&empty, window, cx);
}
window.refresh();
})
.child("Clear selection"),
)
});
let st_esc = state_cell.clone();
let cb_sel_esc = self.on_selection_change.clone();
div()
.id(self.id)
.role(Role::Grid)
.aria_label(self.caption)
.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 ev.keystroke.key.as_str() == "escape" && selected_count > 0 {
let empty = Vec::new();
if !sel_controlled {
st_esc.borrow_mut().selected.clear();
}
if let Some(ref cb) = cb_sel_esc {
cb(&empty, window, cx);
}
window.refresh();
}
})
.child(header)
.child(body)
.child(footer)
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sort_pins_empty_values_at_bottom_in_both_directions() {
let rows = vec![
DataTableRow::new("a").cell("score", 40.0),
DataTableRow::new("b").cell("score", DataCellValue::Empty),
DataTableRow::new("c").cell("score", 10.0),
DataTableRow::new("d").cell("score", 95.0),
];
let asc = sort_data_table_rows(&rows, Some(&SortState::asc("score")));
let asc_keys: Vec<&str> = asc.iter().map(|r| r.key.as_ref()).collect();
assert_eq!(asc_keys, vec!["c", "a", "d", "b"]);
let desc = sort_data_table_rows(&rows, Some(&SortState::desc("score")));
let desc_keys: Vec<&str> = desc.iter().map(|r| r.key.as_ref()).collect();
assert_eq!(desc_keys, vec!["d", "a", "c", "b"]);
}
}