1use std::{
13 cell::RefCell,
14 cmp::Ordering,
15 collections::{HashMap, HashSet},
16 rc::Rc,
17};
18
19use arc_motion::{
20 CubicBezier, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
21};
22use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
23use gpui_kit::{
24 App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
25 ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window,
26 base::StyledExt as _, canvas, div, point, prelude::*, px,
27};
28
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31pub enum SortDirection {
32 Asc,
33 Desc,
34}
35
36#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct SortState {
39 pub key: SharedString,
40 pub direction: SortDirection,
41}
42
43impl SortState {
44 pub fn asc(key: impl Into<SharedString>) -> Self {
45 Self {
46 key: key.into(),
47 direction: SortDirection::Asc,
48 }
49 }
50
51 pub fn desc(key: impl Into<SharedString>) -> Self {
52 Self {
53 key: key.into(),
54 direction: SortDirection::Desc,
55 }
56 }
57}
58
59#[derive(Clone, Debug, PartialEq)]
61pub enum DataCellValue {
62 Text(SharedString),
63 Number(f64),
64 FormattedNumber { value: f64, display: SharedString },
65 Empty,
66}
67
68impl DataCellValue {
69 pub fn is_empty(&self) -> bool {
70 match self {
71 Self::Empty => true,
72 Self::Text(s) => s.trim().is_empty(),
73 Self::Number(_) | Self::FormattedNumber { .. } => false,
74 }
75 }
76
77 pub fn display_text(&self) -> SharedString {
78 match self {
79 Self::Empty => SharedString::from("—"),
80 Self::Text(s) => s.clone(),
81 Self::Number(n) => {
82 if n.fract().abs() < 1e-9 {
83 SharedString::from(format!("{}", *n as i64))
84 } else {
85 SharedString::from(format!("{n:.1}"))
86 }
87 }
88 Self::FormattedNumber { display, .. } => display.clone(),
89 }
90 }
91
92 fn compare_non_empty(&self, other: &Self) -> Ordering {
93 match (self, other) {
94 (
95 Self::Number(a) | Self::FormattedNumber { value: a, .. },
96 Self::Number(b) | Self::FormattedNumber { value: b, .. },
97 ) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
98 _ => self
99 .display_text()
100 .to_lowercase()
101 .cmp(&other.display_text().to_lowercase()),
102 }
103 }
104}
105
106impl From<&str> for DataCellValue {
107 fn from(s: &str) -> Self {
108 if s.is_empty() {
109 Self::Empty
110 } else {
111 Self::Text(SharedString::from(s.to_string()))
112 }
113 }
114}
115
116impl From<String> for DataCellValue {
117 fn from(s: String) -> Self {
118 if s.is_empty() {
119 Self::Empty
120 } else {
121 Self::Text(SharedString::from(s))
122 }
123 }
124}
125
126impl From<f64> for DataCellValue {
127 fn from(n: f64) -> Self {
128 Self::Number(n)
129 }
130}
131
132#[derive(Clone, Debug)]
134pub struct DataColumn {
135 pub key: SharedString,
136 pub label: SharedString,
137 pub sortable: bool,
138 pub numeric: bool,
139 pub width: Option<f32>,
140}
141
142impl DataColumn {
143 pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
144 Self {
145 key: key.into(),
146 label: label.into(),
147 sortable: true,
148 numeric: false,
149 width: None,
150 }
151 }
152
153 pub fn sortable(mut self, sortable: bool) -> Self {
154 self.sortable = sortable;
155 self
156 }
157
158 pub fn numeric(mut self, numeric: bool) -> Self {
159 self.numeric = numeric;
160 self
161 }
162
163 pub fn width(mut self, width_px: f32) -> Self {
164 self.width = Some(width_px);
165 self
166 }
167}
168
169#[derive(Clone, Debug)]
171pub struct DataTableRow {
172 pub key: SharedString,
173 pub cells: HashMap<SharedString, DataCellValue>,
174}
175
176impl DataTableRow {
177 pub fn new(key: impl Into<SharedString>) -> Self {
178 Self {
179 key: key.into(),
180 cells: HashMap::new(),
181 }
182 }
183
184 pub fn cell(
185 mut self,
186 col_key: impl Into<SharedString>,
187 value: impl Into<DataCellValue>,
188 ) -> Self {
189 self.cells.insert(col_key.into(), value.into());
190 self
191 }
192}
193
194pub fn sort_data_table_rows(rows: &[DataTableRow], sort: Option<&SortState>) -> Vec<DataTableRow> {
196 let Some(sort) = sort else {
197 return rows.to_vec();
198 };
199 let mut indexed: Vec<(usize, &DataTableRow)> = rows.iter().enumerate().collect();
200 indexed.sort_by(|(ia, a), (ib, b)| {
201 let va = a.cells.get(&sort.key).unwrap_or(&DataCellValue::Empty);
202 let vb = b.cells.get(&sort.key).unwrap_or(&DataCellValue::Empty);
203 let ea = va.is_empty();
204 let eb = vb.is_empty();
205 if ea || eb {
206 return match (ea, eb) {
207 (true, true) => ia.cmp(ib),
208 (true, false) => Ordering::Greater,
209 (false, true) => Ordering::Less,
210 (false, false) => unreachable!(),
211 };
212 }
213 let ord = va.compare_non_empty(vb);
214 let directed = match sort.direction {
215 SortDirection::Asc => ord,
216 SortDirection::Desc => ord.reverse(),
217 };
218 directed.then_with(|| ia.cmp(ib))
219 });
220 indexed.into_iter().map(|(_, r)| r.clone()).collect()
221}
222
223fn paint_sort_arrow(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
224 let rad = angle_deg.to_radians();
225 let (c, s) = (rad.cos(), rad.sin());
226 let rot = |dx: f32, dy: f32| point(px(cx + dx * c - dy * s), px(cy + dx * s + dy * c));
227 let mut shaft = PathBuilder::stroke(px(1.6));
228 shaft.move_to(rot(0.0, 4.5));
229 shaft.line_to(rot(0.0, -4.5));
230 if let Ok(p) = shaft.build() {
231 window.paint_path(p, color);
232 }
233 let mut head = PathBuilder::stroke(px(1.6));
234 head.move_to(rot(-3.2, -1.2));
235 head.line_to(rot(0.0, -4.5));
236 head.line_to(rot(3.2, -1.2));
237 if let Ok(p) = head.build() {
238 window.paint_path(p, color);
239 }
240}
241
242fn paint_checkbox_mark(
243 cx: f32,
244 cy: f32,
245 checked: bool,
246 mixed: bool,
247 fg: Hsla,
248 window: &mut Window,
249) {
250 if !checked && !mixed {
251 return;
252 }
253 let mut pb = PathBuilder::stroke(px(1.8));
254 if mixed {
255 pb.move_to(point(px(cx - 4.0), px(cy)));
256 pb.line_to(point(px(cx + 4.0), px(cy)));
257 } else {
258 pb.move_to(point(px(cx - 4.2), px(cy + 0.4)));
259 pb.line_to(point(px(cx - 1.2), px(cy + 3.4)));
260 pb.line_to(point(px(cx + 4.6), px(cy - 3.2)));
261 }
262 if let Ok(path) = pb.build() {
263 window.paint_path(path, fg);
264 }
265}
266
267type SortChangeCallback = Rc<dyn Fn(&SortState, &mut Window, &mut App)>;
268type SelectionChangeCallback = Rc<dyn Fn(&Vec<SharedString>, &mut Window, &mut App)>;
269
270#[derive(Clone)]
271struct SortableTableInternal {
272 sort: Option<SortState>,
273 selected: HashSet<SharedString>,
274 anchor_key: Option<SharedString>,
275 hovered_key: Option<SharedString>,
276 last_count: usize,
277 count_dir: i8,
278 count_changed_at: f64,
279 focus_handle: FocusHandle,
280}
281
282#[derive(IntoElement)]
284pub struct SortableDataTable {
285 id: ElementId,
286 caption: SharedString,
287 columns: Vec<DataColumn>,
288 rows: Vec<DataTableRow>,
289 empty_message: SharedString,
290 default_sort: Option<SortState>,
291 selectable: bool,
292 selected_override: Option<Vec<SharedString>>,
293 default_selected: Vec<SharedString>,
294 item_singular: SharedString,
295 item_plural: SharedString,
296 on_sort_change: Option<SortChangeCallback>,
297 on_selection_change: Option<SelectionChangeCallback>,
298}
299
300impl SortableDataTable {
301 pub fn new(
302 id: impl Into<ElementId>,
303 columns: impl IntoIterator<Item = DataColumn>,
304 rows: impl IntoIterator<Item = DataTableRow>,
305 ) -> Self {
306 Self {
307 id: id.into(),
308 caption: SharedString::from("Data table"),
309 columns: columns.into_iter().collect(),
310 rows: rows.into_iter().collect(),
311 empty_message: SharedString::from("No rows to show"),
312 default_sort: None,
313 selectable: false,
314 selected_override: None,
315 default_selected: Vec::new(),
316 item_singular: SharedString::from("row"),
317 item_plural: SharedString::from("rows"),
318 on_sort_change: None,
319 on_selection_change: None,
320 }
321 }
322
323 pub fn caption(mut self, caption: impl Into<SharedString>) -> Self {
324 self.caption = caption.into();
325 self
326 }
327
328 pub fn empty_message(mut self, message: impl Into<SharedString>) -> Self {
329 self.empty_message = message.into();
330 self
331 }
332
333 pub fn default_sort(mut self, sort: SortState) -> Self {
334 self.default_sort = Some(sort);
335 self
336 }
337
338 pub fn selectable(mut self, selectable: bool) -> Self {
339 self.selectable = selectable;
340 self
341 }
342
343 pub fn default_selected(
344 mut self,
345 keys: impl IntoIterator<Item = impl Into<SharedString>>,
346 ) -> Self {
347 self.default_selected = keys.into_iter().map(Into::into).collect();
348 self
349 }
350
351 pub fn selected(mut self, keys: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
352 self.selected_override = Some(keys.into_iter().map(Into::into).collect());
353 self
354 }
355
356 pub fn item_name(
357 mut self,
358 singular: impl Into<SharedString>,
359 plural: impl Into<SharedString>,
360 ) -> Self {
361 self.item_singular = singular.into();
362 self.item_plural = plural.into();
363 self
364 }
365
366 pub fn on_sort_change(
367 mut self,
368 cb: impl Fn(&SortState, &mut Window, &mut App) + 'static,
369 ) -> Self {
370 self.on_sort_change = Some(Rc::new(cb));
371 self
372 }
373
374 pub fn on_selection_change(
375 mut self,
376 cb: impl Fn(&Vec<SharedString>, &mut Window, &mut App) + 'static,
377 ) -> Self {
378 self.on_selection_change = Some(Rc::new(cb));
379 self
380 }
381}
382
383impl RenderOnce for SortableDataTable {
384 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
385 let theme = cx.arc_theme().clone();
386 let colors = theme.colors;
387 let reduced = is_reduced_motion(cx);
388 let now = motion_now(cx);
389
390 let state_cell = window
391 .use_keyed_state(
392 ElementId::NamedChild(self.id.clone().into(), SharedString::from("sdt-state")),
393 cx,
394 |_, cx| {
395 Rc::new(RefCell::new(SortableTableInternal {
396 sort: self.default_sort.clone(),
397 selected: self.default_selected.iter().cloned().collect(),
398 anchor_key: None,
399 hovered_key: None,
400 last_count: self.rows.len(),
401 count_dir: 1,
402 count_changed_at: now - 1.0,
403 focus_handle: cx.focus_handle(),
404 }))
405 },
406 )
407 .read(cx)
408 .clone();
409
410 let sel_controlled = self.selected_override.is_some();
411 let (active_sort, selected_set, hovered_key, focus_handle) = {
412 let mut st = state_cell.borrow_mut();
413 if let Some(ref ov) = self.selected_override {
414 st.selected = ov.iter().cloned().collect();
415 }
416 (
417 st.sort.clone(),
418 st.selected.clone(),
419 st.hovered_key.clone(),
420 st.focus_handle.clone(),
421 )
422 };
423
424 let sorted_rows = sort_data_table_rows(&self.rows, active_sort.as_ref());
425 let ordered_keys: Vec<SharedString> = sorted_rows.iter().map(|r| r.key.clone()).collect();
426 let selected_count = ordered_keys
427 .iter()
428 .filter(|k| selected_set.contains(*k))
429 .count();
430 let all_selected = !ordered_keys.is_empty() && selected_count == ordered_keys.len();
431 let some_selected = selected_count > 0 && !all_selected;
432
433 let shown_count = if selected_count > 0 {
434 selected_count
435 } else {
436 ordered_keys.len()
437 };
438 let (count_dir, count_elapsed) = {
439 let mut st = state_cell.borrow_mut();
440 if st.last_count != shown_count {
441 st.count_dir = if shown_count > st.last_count { 1 } else { -1 };
442 st.last_count = shown_count;
443 st.count_changed_at = now;
444 }
445 let dt = (now - st.count_changed_at).max(0.0);
446 if !reduced && dt < 0.26 {
447 window.request_animation_frame();
448 }
449 (st.count_dir, dt)
450 };
451
452 let sorted_col_tint = oklab_mix(colors.foreground, colors.surface, 0.028);
453 let row_hover_bg = oklab_mix(colors.foreground, colors.surface, 0.04);
454 let row_selected_bg = oklab_mix(colors.accent, colors.surface, 0.08);
455
456 let mut header = div()
458 .w_full()
459 .h(px(36.0))
460 .px(Spacing::S3)
461 .bg(colors.surface_muted)
462 .border_b_1()
463 .border_color(colors.border)
464 .flex()
465 .flex_row()
466 .items_center()
467 .gap(Spacing::S3);
468
469 if self.selectable {
470 let st_all = state_cell.clone();
471 let keys_all = ordered_keys.clone();
472 let cb_sel = self.on_selection_change.clone();
473 let box_bg = if all_selected || some_selected {
474 colors.accent
475 } else {
476 colors.surface
477 };
478 let box_border = if all_selected || some_selected {
479 colors.accent
480 } else {
481 colors.border_strong
482 };
483 let fg_acc = colors.accent_foreground;
484 header = header.child(
485 div()
486 .id(ElementId::NamedChild(
487 self.id.clone().into(),
488 SharedString::from("sdt-select-all"),
489 ))
490 .w(px(28.0))
491 .flex_none()
492 .flex()
493 .items_center()
494 .justify_center()
495 .cursor_pointer()
496 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
497 let next_vec = if all_selected {
498 Vec::new()
499 } else {
500 keys_all.clone()
501 };
502 if !sel_controlled {
503 st_all.borrow_mut().selected = next_vec.iter().cloned().collect();
504 }
505 if let Some(ref cb) = cb_sel {
506 cb(&next_vec, window, cx);
507 }
508 window.refresh();
509 })
510 .child(
511 div()
512 .w(px(16.0))
513 .h(px(16.0))
514 .rounded(px(4.0))
515 .border_1()
516 .border_color(box_border)
517 .bg(box_bg)
518 .child(
519 canvas(
520 |_, _, _| {},
521 move |bounds, _, window, _| {
522 let cx_p = f32::from(bounds.origin.x)
523 + f32::from(bounds.size.width) * 0.5;
524 let cy_p = f32::from(bounds.origin.y)
525 + f32::from(bounds.size.height) * 0.5;
526 paint_checkbox_mark(
527 cx_p,
528 cy_p,
529 all_selected,
530 some_selected,
531 fg_acc,
532 window,
533 );
534 },
535 )
536 .size_full(),
537 ),
538 ),
539 );
540 }
541
542 for col in &self.columns {
543 let is_sorted = active_sort.as_ref().is_some_and(|s| s.key == col.key);
544 let is_desc = active_sort
545 .as_ref()
546 .is_some_and(|s| s.key == col.key && s.direction == SortDirection::Desc);
547 let target_angle = if is_desc { 180.0 } else { 0.0 };
548 let angle = if reduced {
549 target_angle
550 } else {
551 arc_spring_with_options(
552 ElementId::NamedChild(
553 self.id.clone().into(),
554 SharedString::from(format!("sdt-arrow-{}", col.key)),
555 ),
556 target_angle,
557 SpringOptions::new(SpringSpec::visual(0.20, 0.0))
558 .with_initial_value(target_angle),
559 window,
560 cx,
561 )
562 .value
563 };
564
565 let mut th = div()
566 .min_w(px(0.0))
567 .h_full()
568 .flex()
569 .flex_row()
570 .items_center()
571 .gap(px(5.0))
572 .text_size(Typography::TEXT_XS)
573 .font_medium()
574 .text_color(if is_sorted {
575 colors.foreground
576 } else {
577 colors.text_muted
578 });
579 if let Some(w) = col.width {
580 th = th.w(px(w)).flex_none();
581 } else {
582 th = th.flex_1();
583 }
584 if col.numeric {
585 th = th.justify_end();
586 }
587
588 let header_cell: gpui_kit::AnyElement = if col.sortable {
589 let st_sort = state_cell.clone();
590 let col_key = col.key.clone();
591 let cb_sort = self.on_sort_change.clone();
592 let arrow_col = if is_sorted {
593 colors.foreground
594 } else {
595 colors.text_muted.opacity(0.35)
596 };
597 th.id(ElementId::NamedChild(
598 self.id.clone().into(),
599 SharedString::from(format!("sdt-th-{}", col.key)),
600 ))
601 .cursor_pointer()
602 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
603 let next = {
604 let cur = st_sort.borrow().sort.clone();
605 match cur {
606 Some(ref s)
607 if s.key == col_key && s.direction == SortDirection::Asc =>
608 {
609 SortState::desc(col_key.clone())
610 }
611 _ => SortState::asc(col_key.clone()),
612 }
613 };
614 st_sort.borrow_mut().sort = Some(next.clone());
615 if let Some(ref cb) = cb_sort {
616 cb(&next, window, cx);
617 }
618 window.refresh();
619 })
620 .child(col.label.clone())
621 .child(
622 div().w(px(14.0)).h(px(14.0)).flex_none().child(
623 canvas(
624 |_, _, _| {},
625 move |bounds, _, window, _| {
626 let cx_p =
627 f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
628 let cy_p = f32::from(bounds.origin.y)
629 + f32::from(bounds.size.height) * 0.5;
630 paint_sort_arrow(cx_p, cy_p, angle, arrow_col, window);
631 },
632 )
633 .size_full(),
634 ),
635 )
636 .into_any_element()
637 } else {
638 th.child(col.label.clone()).into_any_element()
639 };
640
641 header = header.child(header_cell);
642 }
643
644 let mut body = div().w_full().flex().flex_col();
646 if sorted_rows.is_empty() {
647 body = body.child(
648 div()
649 .w_full()
650 .py(Spacing::S8)
651 .text_center()
652 .text_size(Typography::TEXT_SM)
653 .text_color(colors.text_muted)
654 .child(self.empty_message.clone()),
655 );
656 } else {
657 for row in &sorted_rows {
658 let row_key = row.key.clone();
659 let is_selected = selected_set.contains(&row_key);
660 let is_hovered = hovered_key.as_ref() == Some(&row_key);
661 let row_bg = if is_selected {
662 row_selected_bg
663 } else if is_hovered {
664 row_hover_bg
665 } else {
666 colors.surface
667 };
668
669 let st_hover = state_cell.clone();
670 let rk_hover = row_key.clone();
671 let st_click = state_cell.clone();
672 let rk_click = row_key.clone();
673 let keys_click = ordered_keys.clone();
674 let cb_sel_row = self.on_selection_change.clone();
675 let selectable_row = self.selectable;
676 let fh_row = focus_handle.clone();
677
678 let mut row_el = div()
679 .id(ElementId::NamedChild(
680 self.id.clone().into(),
681 SharedString::from(format!("sdt-row-{row_key}")),
682 ))
683 .role(Role::Row)
684 .w_full()
685 .min_h(px(38.0))
686 .px(Spacing::S3)
687 .bg(row_bg)
688 .border_b_1()
689 .border_color(colors.border_subtle)
690 .flex()
691 .flex_row()
692 .items_center()
693 .gap(Spacing::S3)
694 .when(selectable_row, |el| el.cursor_pointer())
695 .on_hover(move |hovered, window, _| {
696 let mut st = st_hover.borrow_mut();
697 if *hovered {
698 st.hovered_key = Some(rk_hover.clone());
699 } else if st.hovered_key.as_ref() == Some(&rk_hover) {
700 st.hovered_key = None;
701 }
702 window.refresh();
703 })
704 .on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
705 if !selectable_row {
706 return;
707 }
708 fh_row.focus(window, cx);
709 let next_vec: Vec<SharedString> = {
710 let mut st = st_click.borrow_mut();
711 let turn_on = !st.selected.contains(&rk_click);
712 let range_keys: Vec<SharedString> = if ev.modifiers.shift {
713 if let (Some(anchor), Some(to)) = (
714 st.anchor_key
715 .as_ref()
716 .and_then(|a| keys_click.iter().position(|k| k == a)),
717 keys_click.iter().position(|k| k == &rk_click),
718 ) {
719 let (lo, hi) = if anchor <= to {
720 (anchor, to)
721 } else {
722 (to, anchor)
723 };
724 keys_click[lo..=hi].to_vec()
725 } else {
726 vec![rk_click.clone()]
727 }
728 } else {
729 vec![rk_click.clone()]
730 };
731 for k in range_keys {
732 if turn_on {
733 st.selected.insert(k);
734 } else {
735 st.selected.remove(&k);
736 }
737 }
738 st.anchor_key = Some(rk_click.clone());
739 keys_click
740 .iter()
741 .filter(|k| st.selected.contains(*k))
742 .cloned()
743 .collect()
744 };
745 if let Some(ref cb) = cb_sel_row {
746 cb(&next_vec, window, cx);
747 }
748 window.refresh();
749 });
750
751 if self.selectable {
752 let box_bg = if is_selected {
753 colors.accent
754 } else {
755 colors.surface
756 };
757 let box_border = if is_selected {
758 colors.accent
759 } else {
760 colors.border_strong
761 };
762 let fg_acc = colors.accent_foreground;
763 row_el = row_el.child(
764 div()
765 .w(px(28.0))
766 .flex_none()
767 .flex()
768 .items_center()
769 .justify_center()
770 .child(
771 div()
772 .w(px(16.0))
773 .h(px(16.0))
774 .rounded(px(4.0))
775 .border_1()
776 .border_color(box_border)
777 .bg(box_bg)
778 .child(
779 canvas(
780 |_, _, _| {},
781 move |bounds, _, window, _| {
782 let cx_p = f32::from(bounds.origin.x)
783 + f32::from(bounds.size.width) * 0.5;
784 let cy_p = f32::from(bounds.origin.y)
785 + f32::from(bounds.size.height) * 0.5;
786 paint_checkbox_mark(
787 cx_p,
788 cy_p,
789 is_selected,
790 false,
791 fg_acc,
792 window,
793 );
794 },
795 )
796 .size_full(),
797 ),
798 ),
799 );
800 }
801
802 for (col_idx, col) in self.columns.iter().enumerate() {
803 let is_sorted_col = active_sort.as_ref().is_some_and(|s| s.key == col.key);
804 let cell_val = row.cells.get(&col.key).unwrap_or(&DataCellValue::Empty);
805 let mut td = div()
806 .min_w(px(0.0))
807 .h(px(38.0))
808 .px(px(2.0))
809 .flex()
810 .flex_row()
811 .items_center()
812 .text_size(Typography::TEXT_SM)
813 .text_color(if cell_val.is_empty() {
814 colors.text_muted
815 } else if col_idx == 0 {
816 colors.foreground
817 } else {
818 colors.text_secondary
819 });
820 if is_sorted_col && !is_selected && !is_hovered {
821 td = td.bg(sorted_col_tint);
822 }
823 if let Some(w) = col.width {
824 td = td.w(px(w)).flex_none();
825 } else {
826 td = td.flex_1();
827 }
828 if col.numeric {
829 td = td.justify_end();
830 }
831 if col_idx == 0 {
832 td = td.font_medium();
833 }
834 row_el =
835 row_el.child(td.child(div().truncate().child(cell_val.display_text())));
836 }
837
838 body = body.child(row_el);
839 }
840 }
841
842 let count_t = if reduced {
844 1.0
845 } else {
846 CubicBezier::new(0.16, 1.0, 0.3, 1.0)
847 .sample((count_elapsed / 0.24).clamp(0.0, 1.0) as f32)
848 };
849 let count_y = (1.0 - count_t) * 5.0 * count_dir as f32;
850 let noun = if selected_count > 0 {
851 SharedString::from("selected")
852 } else if ordered_keys.len() == 1 {
853 self.item_singular.clone()
854 } else {
855 self.item_plural.clone()
856 };
857
858 let st_clear = state_cell.clone();
859 let cb_sel_clear = self.on_selection_change.clone();
860 let footer = div()
861 .w_full()
862 .px(Spacing::S3)
863 .py(Spacing::S2)
864 .bg(colors.surface_muted)
865 .flex()
866 .flex_row()
867 .items_center()
868 .justify_between()
869 .text_size(Typography::TEXT_XS)
870 .text_color(colors.text_muted)
871 .child(
872 div()
873 .flex()
874 .flex_row()
875 .items_center()
876 .gap(px(5.0))
877 .child(
878 div()
879 .relative()
880 .top(px(count_y))
881 .opacity(count_t)
882 .font_medium()
883 .text_color(colors.foreground)
884 .child(format!("{shown_count}")),
885 )
886 .child(noun),
887 )
888 .when(selected_count > 0, |el| {
889 el.child(
890 div()
891 .id(ElementId::NamedChild(
892 self.id.clone().into(),
893 SharedString::from("sdt-clear"),
894 ))
895 .px(Spacing::S2)
896 .py(px(2.0))
897 .rounded(Radii::CONTROL)
898 .text_color(colors.foreground)
899 .cursor_pointer()
900 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
901 let empty = Vec::new();
902 if !sel_controlled {
903 st_clear.borrow_mut().selected.clear();
904 }
905 if let Some(ref cb) = cb_sel_clear {
906 cb(&empty, window, cx);
907 }
908 window.refresh();
909 })
910 .child("Clear selection"),
911 )
912 });
913
914 let st_esc = state_cell.clone();
915 let cb_sel_esc = self.on_selection_change.clone();
916
917 div()
918 .id(self.id)
919 .role(Role::Grid)
920 .aria_label(self.caption)
921 .track_focus(&focus_handle)
922 .w_full()
923 .rounded(Radii::PANEL)
924 .border_1()
925 .border_color(colors.border)
926 .bg(colors.surface)
927 .overflow_hidden()
928 .on_key_down(move |ev: &KeyDownEvent, window, cx| {
929 if ev.keystroke.key.as_str() == "escape" && selected_count > 0 {
930 let empty = Vec::new();
931 if !sel_controlled {
932 st_esc.borrow_mut().selected.clear();
933 }
934 if let Some(ref cb) = cb_sel_esc {
935 cb(&empty, window, cx);
936 }
937 window.refresh();
938 }
939 })
940 .child(header)
941 .child(body)
942 .child(footer)
943 .into_any_element()
944 }
945}
946
947#[cfg(test)]
948mod tests {
949 use super::*;
950
951 #[test]
952 fn sort_pins_empty_values_at_bottom_in_both_directions() {
953 let rows = vec![
954 DataTableRow::new("a").cell("score", 40.0),
955 DataTableRow::new("b").cell("score", DataCellValue::Empty),
956 DataTableRow::new("c").cell("score", 10.0),
957 DataTableRow::new("d").cell("score", 95.0),
958 ];
959
960 let asc = sort_data_table_rows(&rows, Some(&SortState::asc("score")));
961 let asc_keys: Vec<&str> = asc.iter().map(|r| r.key.as_ref()).collect();
962 assert_eq!(asc_keys, vec!["c", "a", "d", "b"]);
963
964 let desc = sort_data_table_rows(&rows, Some(&SortState::desc("score")));
965 let desc_keys: Vec<&str> = desc.iter().map(|r| r.key.as_ref()).collect();
966 assert_eq!(desc_keys, vec!["d", "a", "c", "b"]);
967 }
968}