1use std::{cell::RefCell, f32::consts::PI, rc::Rc};
2
3use gpui::{
4 AccessibleAction, AnyElement, App, ClickEvent, CursorStyle, ElementId, FocusHandle, Hsla,
5 InteractiveElement, IntoElement, KeyDownEvent, ParentElement, Pixels, RenderOnce, SharedString,
6 StatefulInteractiveElement, StyleRefinement, Styled, Window, canvas, div,
7 prelude::FluentBuilder, px, radians, transparent_black,
8};
9use gpui_base::{
10 StyledExt as _, Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow,
11};
12use gpui_material_components::{Icon, IconName, Text};
13use gpui_material_foundation::{
14 FocusRingPlacement, InteractionFeedback, InteractionState, ThemeScope, color,
15 control_feedback::{FeedbackState, activate_feedback, feedback_target, ripple_state},
16 current_material_theme, move_roving_focus, resolve_edges,
17};
18use gpui_material_theme::{
19 ColorRole, CornerRole, CornerShape, Density, Direction, LogicalEdges, TypeRole,
20};
21
22const DEFAULT_HEADER_HEIGHT: f32 = 48.0;
23const DEFAULT_ROW_HEIGHT: f32 = 52.0;
24const MIN_ROW_HEIGHT: f32 = 36.0;
25const DEFAULT_CELL_PADDING: LogicalEdges = LogicalEdges::symmetric(16.0, 10.0);
26
27type SortHandler = Rc<dyn Fn(&SharedString, SortDirection, &mut Window, &mut App)>;
28type RowSelectHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
29type RowActivateHandler = Rc<dyn Fn(&mut Window, &mut App)>;
30
31#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33pub enum ColumnAlignment {
34 #[default]
36 Start,
37 Center,
39 End,
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum SortDirection {
46 Ascending,
48 Descending,
50}
51
52impl SortDirection {
53 pub const fn toggled(self) -> Self {
55 match self {
56 Self::Ascending => Self::Descending,
57 Self::Descending => Self::Ascending,
58 }
59 }
60
61 pub const fn next_from(current: Option<Self>) -> Self {
63 match current {
64 None | Some(Self::Descending) => Self::Ascending,
65 Some(Self::Ascending) => Self::Descending,
66 }
67 }
68}
69
70#[derive(Clone, Copy, Debug, Default, PartialEq)]
74pub struct DataTableColors {
75 pub container: Option<Hsla>,
77 pub header_container: Option<Hsla>,
79 pub header_content: Option<Hsla>,
81 pub row_container: Option<Hsla>,
83 pub striped_row_container: Option<Hsla>,
85 pub row_content: Option<Hsla>,
87 pub selected_row_container: Option<Hsla>,
89 pub selected_row_content: Option<Hsla>,
91 pub disabled_content: Option<Hsla>,
93 pub divider: Option<Hsla>,
95 pub border: Option<Hsla>,
97 pub caption: Option<Hsla>,
99 pub sort_indicator: Option<Hsla>,
101}
102
103#[derive(Clone, Debug, PartialEq)]
105pub struct DataTableColumn {
106 id: SharedString,
107 label: SharedString,
108 alignment: ColumnAlignment,
109 width: Option<Pixels>,
110 min_width: Option<Pixels>,
111 weight: f32,
112 sortable: bool,
113 sort_direction: Option<SortDirection>,
114 disabled: bool,
115}
116
117impl DataTableColumn {
118 pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
120 Self {
121 id: id.into(),
122 label: label.into(),
123 alignment: ColumnAlignment::Start,
124 width: None,
125 min_width: None,
126 weight: 1.0,
127 sortable: false,
128 sort_direction: None,
129 disabled: false,
130 }
131 }
132
133 pub fn alignment(mut self, alignment: ColumnAlignment) -> Self {
135 self.alignment = alignment;
136 self
137 }
138
139 pub fn width(mut self, width: Pixels) -> Self {
141 if f32::from(width).is_finite() && width > px(0.) {
142 self.width = Some(width);
143 }
144 self
145 }
146
147 pub fn min_width(mut self, width: Pixels) -> Self {
149 if f32::from(width).is_finite() && width >= px(0.) {
150 self.min_width = Some(width);
151 }
152 self
153 }
154
155 pub fn weight(mut self, weight: f32) -> Self {
157 if weight.is_finite() && weight > 0.0 {
158 self.weight = weight;
159 }
160 self
161 }
162
163 pub fn sortable(mut self, sortable: bool) -> Self {
165 self.sortable = sortable;
166 self
167 }
168
169 pub fn sort_direction(mut self, direction: Option<SortDirection>) -> Self {
173 if direction.is_some() {
174 self.sortable = true;
175 }
176 self.sort_direction = direction;
177 self
178 }
179
180 pub fn disabled(mut self, disabled: bool) -> Self {
182 self.disabled = disabled;
183 self
184 }
185
186 pub fn id(&self) -> &SharedString {
188 &self.id
189 }
190
191 pub fn label(&self) -> &SharedString {
193 &self.label
194 }
195}
196
197enum CellContent {
198 Text(SharedString),
199 Custom(AnyElement),
200}
201
202pub struct DataTableCell {
204 content: CellContent,
205 alignment: Option<ColumnAlignment>,
206 muted: bool,
207}
208
209impl DataTableCell {
210 pub fn text(value: impl Into<SharedString>) -> Self {
212 Self {
213 content: CellContent::Text(value.into()),
214 alignment: None,
215 muted: false,
216 }
217 }
218
219 pub fn custom(element: impl IntoElement) -> Self {
221 Self {
222 content: CellContent::Custom(element.into_any_element()),
223 alignment: None,
224 muted: false,
225 }
226 }
227
228 pub fn alignment(mut self, alignment: ColumnAlignment) -> Self {
230 self.alignment = Some(alignment);
231 self
232 }
233
234 pub fn muted(mut self, muted: bool) -> Self {
236 self.muted = muted;
237 self
238 }
239}
240
241impl From<&'static str> for DataTableCell {
242 fn from(value: &'static str) -> Self {
243 Self::text(value)
244 }
245}
246
247impl From<String> for DataTableCell {
248 fn from(value: String) -> Self {
249 Self::text(value)
250 }
251}
252
253impl From<SharedString> for DataTableCell {
254 fn from(value: SharedString) -> Self {
255 Self::text(value)
256 }
257}
258
259pub struct DataTableRow {
261 id: SharedString,
262 cells: Vec<DataTableCell>,
263 selected: bool,
264 disabled: bool,
265 accessible_label: Option<SharedString>,
266 on_activate: Option<RowActivateHandler>,
267 focus: Option<FocusHandle>,
268}
269
270impl DataTableRow {
271 pub fn new(
273 id: impl Into<SharedString>,
274 cells: impl IntoIterator<Item = impl Into<DataTableCell>>,
275 ) -> Self {
276 Self {
277 id: id.into(),
278 cells: cells.into_iter().map(Into::into).collect(),
279 selected: false,
280 disabled: false,
281 accessible_label: None,
282 on_activate: None,
283 focus: None,
284 }
285 }
286
287 pub fn selected(mut self, selected: bool) -> Self {
289 self.selected = selected;
290 self
291 }
292
293 pub fn disabled(mut self, disabled: bool) -> Self {
295 self.disabled = disabled;
296 self
297 }
298
299 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
301 self.accessible_label = Some(label.into());
302 self
303 }
304
305 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
307 self.on_activate = Some(Rc::new(handler));
308 self
309 }
310
311 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
313 self.focus = Some(focus.clone());
314 self
315 }
316}
317
318#[derive(IntoElement)]
324pub struct DataTable {
325 id: ElementId,
326 columns: Vec<DataTableColumn>,
327 rows: Vec<DataTableRow>,
328 caption: Option<SharedString>,
329 accessible_label: Option<SharedString>,
330 total_row_count: Option<usize>,
331 total_column_count: Option<usize>,
332 cell_padding: LogicalEdges,
333 header_height: Option<Pixels>,
334 row_height: Option<Pixels>,
335 shape: Option<CornerShape>,
336 colors: DataTableColors,
337 show_row_dividers: bool,
338 striped: bool,
339 on_sort: Option<SortHandler>,
340 on_row_select: Option<RowSelectHandler>,
341 style: StyleRefinement,
342}
343
344impl DataTable {
345 pub fn new(id: impl Into<ElementId>) -> Self {
347 Self {
348 id: id.into(),
349 columns: Vec::new(),
350 rows: Vec::new(),
351 caption: None,
352 accessible_label: None,
353 total_row_count: None,
354 total_column_count: None,
355 cell_padding: DEFAULT_CELL_PADDING,
356 header_height: None,
357 row_height: None,
358 shape: None,
359 colors: DataTableColors::default(),
360 show_row_dividers: true,
361 striped: false,
362 on_sort: None,
363 on_row_select: None,
364 style: StyleRefinement::default(),
365 }
366 }
367
368 pub fn column(mut self, column: DataTableColumn) -> Self {
370 self.columns.push(column);
371 self
372 }
373
374 pub fn columns(mut self, columns: impl IntoIterator<Item = DataTableColumn>) -> Self {
376 self.columns.extend(columns);
377 self
378 }
379
380 pub fn row(mut self, row: DataTableRow) -> Self {
382 self.rows.push(row);
383 self
384 }
385
386 pub fn rows(mut self, rows: impl IntoIterator<Item = DataTableRow>) -> Self {
388 self.rows.extend(rows);
389 self
390 }
391
392 pub fn caption(mut self, caption: impl Into<SharedString>) -> Self {
394 self.caption = Some(caption.into());
395 self
396 }
397
398 pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
400 self.accessible_label = Some(label.into());
401 self
402 }
403
404 pub fn total_row_count(mut self, count: usize) -> Self {
406 self.total_row_count = Some(count);
407 self
408 }
409
410 pub fn total_column_count(mut self, count: usize) -> Self {
412 self.total_column_count = Some(count);
413 self
414 }
415
416 pub fn cell_padding(mut self, padding: LogicalEdges) -> Self {
418 self.cell_padding = padding.sanitize();
419 self
420 }
421
422 pub fn header_height(mut self, height: Pixels) -> Self {
424 if f32::from(height).is_finite() && height > px(0.) {
425 self.header_height = Some(height);
426 }
427 self
428 }
429
430 pub fn row_height(mut self, height: Pixels) -> Self {
432 if f32::from(height).is_finite() && height > px(0.) {
433 self.row_height = Some(height);
434 }
435 self
436 }
437
438 pub fn shape(mut self, shape: CornerShape) -> Self {
440 self.shape = Some(shape);
441 self
442 }
443
444 pub fn colors(mut self, colors: DataTableColors) -> Self {
446 self.colors = colors;
447 self
448 }
449
450 pub fn show_row_dividers(mut self, show: bool) -> Self {
452 self.show_row_dividers = show;
453 self
454 }
455
456 pub fn striped(mut self, striped: bool) -> Self {
458 self.striped = striped;
459 self
460 }
461
462 pub fn on_sort(
466 mut self,
467 handler: impl Fn(&SharedString, SortDirection, &mut Window, &mut App) + 'static,
468 ) -> Self {
469 self.on_sort = Some(Rc::new(handler));
470 self
471 }
472
473 pub fn on_row_select(
475 mut self,
476 handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
477 ) -> Self {
478 self.on_row_select = Some(Rc::new(handler));
479 self
480 }
481}
482
483impl Styled for DataTable {
484 fn style(&mut self) -> &mut StyleRefinement {
485 &mut self.style
486 }
487}
488
489pub(crate) fn table_header_height(density: Density, override_height: Option<Pixels>) -> Pixels {
490 override_height.unwrap_or_else(|| {
491 px(density
492 .visual_size(DEFAULT_HEADER_HEIGHT)
493 .max(MIN_ROW_HEIGHT))
494 })
495}
496
497pub(crate) fn table_row_height(density: Density, override_height: Option<Pixels>) -> Pixels {
498 override_height
499 .unwrap_or_else(|| px(density.visual_size(DEFAULT_ROW_HEIGHT).max(MIN_ROW_HEIGHT)))
500}
501
502struct ResolvedTableColors {
503 container: Hsla,
504 header_container: Hsla,
505 header_content: Hsla,
506 row_container: Hsla,
507 striped_row_container: Hsla,
508 row_content: Hsla,
509 muted_content: Hsla,
510 selected_row_container: Hsla,
511 selected_row_content: Hsla,
512 disabled_content: Hsla,
513 divider: Hsla,
514 border: Hsla,
515 caption: Hsla,
516 sort_indicator: Hsla,
517 focus_ring: Hsla,
518}
519
520impl DataTableColors {
521 fn resolve(self, scheme: &gpui_material_theme::ColorScheme) -> ResolvedTableColors {
522 let tone = |role| color(scheme.color(role));
523 ResolvedTableColors {
524 container: self
525 .container
526 .unwrap_or_else(|| tone(ColorRole::SurfaceContainerLow)),
527 header_container: self
528 .header_container
529 .unwrap_or_else(|| tone(ColorRole::SurfaceContainer)),
530 header_content: self
531 .header_content
532 .unwrap_or_else(|| tone(ColorRole::OnSurfaceVariant)),
533 row_container: self.row_container.unwrap_or_else(transparent_black),
534 striped_row_container: self
535 .striped_row_container
536 .unwrap_or_else(|| tone(ColorRole::SurfaceContainerLowest)),
537 row_content: self
538 .row_content
539 .unwrap_or_else(|| tone(ColorRole::OnSurface)),
540 muted_content: tone(ColorRole::OnSurfaceVariant),
541 selected_row_container: self
542 .selected_row_container
543 .unwrap_or_else(|| tone(ColorRole::SecondaryContainer)),
544 selected_row_content: self
545 .selected_row_content
546 .unwrap_or_else(|| tone(ColorRole::OnSecondaryContainer)),
547 disabled_content: self
548 .disabled_content
549 .unwrap_or_else(|| tone(ColorRole::OnSurface).opacity(0.38)),
550 divider: self
551 .divider
552 .unwrap_or_else(|| tone(ColorRole::OutlineVariant)),
553 border: self
554 .border
555 .unwrap_or_else(|| tone(ColorRole::OutlineVariant)),
556 caption: self
557 .caption
558 .unwrap_or_else(|| tone(ColorRole::OnSurfaceVariant)),
559 sort_indicator: self
560 .sort_indicator
561 .unwrap_or_else(|| tone(ColorRole::Primary)),
562 focus_ring: tone(ColorRole::Secondary),
563 }
564 }
565}
566
567fn apply_column_sizing<E: Styled>(el: E, column: &DataTableColumn) -> E {
568 let el = if let Some(width) = column.width {
569 el.w(width).flex_none()
570 } else {
571 el.flex_1().min_w_0()
572 };
573 let el = match column.min_width {
574 Some(min_width) => el.min_w(min_width),
575 None => el,
576 };
577 if column.width.is_none() && (column.weight - 1.0).abs() > f32::EPSILON {
578 let mut el = el;
579 el.style().flex_grow = Some(column.weight);
580 el
581 } else {
582 el
583 }
584}
585
586fn apply_cell_alignment<E: Styled>(el: E, alignment: ColumnAlignment) -> E {
587 match alignment {
590 ColumnAlignment::Start => el.justify_start(),
591 ColumnAlignment::Center => el.justify_center(),
592 ColumnAlignment::End => el.justify_end(),
593 }
594}
595
596fn render_feedback_overlay(
597 feedback: Rc<RefCell<FeedbackState>>,
598 interaction: InteractionState,
599 ink: Hsla,
600 focus_ring: Hsla,
601 direction: Direction,
602 reduced_motion: bool,
603) -> AnyElement {
604 let corners = CornerRole::None.shape();
605 let prepaint_feedback = feedback.clone();
606 canvas(
607 move |bounds, window, _| {
608 prepaint_feedback
609 .borrow_mut()
610 .set_rounded_shape(bounds, corners, direction, window);
611 },
612 move |_, _, window, cx| {
613 let state = feedback.borrow();
614 let Some(shape) = state.shape() else {
615 return;
616 };
617 let now = cx.background_executor().now();
618 InteractionFeedback::new(interaction, ink, focus_ring)
619 .focus_ring_placement(FocusRingPlacement::Inset)
620 .paint(shape, state.ripple(), now, reduced_motion, window);
621 },
622 )
623 .absolute()
624 .inset_0()
625 .into_any_element()
626}
627
628fn row_default_label(row: &DataTableRow) -> SharedString {
629 if let Some(label) = &row.accessible_label {
630 return label.clone();
631 }
632 let text_parts: Vec<&str> = row
633 .cells
634 .iter()
635 .filter_map(|cell| match &cell.content {
636 CellContent::Text(text) if !text.is_empty() => Some(text.as_ref()),
637 _ => None,
638 })
639 .collect();
640 if text_parts.is_empty() {
641 row.id.clone()
642 } else {
643 text_parts.join(", ").into()
644 }
645}
646
647impl RenderOnce for DataTable {
648 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
649 window.with_element_namespace((self.id.clone(), "material-data-table"), |window| {
650 let theme = current_material_theme(window, cx).clone();
651 let direction = theme.layout.direction;
652 let rtl = direction == Direction::Rtl;
653 let density = theme.layout.density;
654 let reduced_motion = cx.reduce_motion();
655 let colors = self.colors.resolve(&theme.colors);
656 let padding = resolve_edges(self.cell_padding, direction);
657 let header_height = table_header_height(density, self.header_height);
658 let row_height = table_row_height(density, self.row_height);
659 let shape = self.shape.unwrap_or_else(|| CornerRole::Medium.shape());
660 let radii = shape.radii(100.0, 100.0, direction);
661
662 let total_rows = self
663 .total_row_count
664 .unwrap_or_else(|| self.rows.len() + usize::from(!self.columns.is_empty()));
665 let total_columns = self.total_column_count.unwrap_or(self.columns.len());
666
667 let on_sort = self.on_sort;
668 let on_row_select = self.on_row_select;
669
670 let row_focus: Vec<FocusHandle> = self
672 .rows
673 .iter()
674 .map(|row| {
675 row.focus.clone().unwrap_or_else(|| {
676 window
677 .use_keyed_state(
678 (ElementId::from(row.id.clone()), "table-row-focus"),
679 cx,
680 |_, cx| cx.focus_handle(),
681 )
682 .read(cx)
683 .clone()
684 })
685 })
686 .collect();
687 let row_enabled: Vec<bool> = self
688 .rows
689 .iter()
690 .map(|row| !row.disabled && (on_row_select.is_some() || row.on_activate.is_some()))
691 .collect();
692 let row_tab_stop = row_focus
693 .iter()
694 .enumerate()
695 .position(|(ix, handle)| row_enabled[ix] && handle.is_focused(window))
696 .or_else(|| {
697 self.rows
698 .iter()
699 .enumerate()
700 .position(|(ix, row)| row_enabled[ix] && row.selected)
701 })
702 .or_else(|| row_enabled.iter().position(|enabled| *enabled));
703
704 let mut header_cells = Vec::with_capacity(self.columns.len());
705 for (col_ix, column) in self.columns.iter().enumerate() {
706 let head_id = ElementId::from((self.id.clone(), format!("col-{}", column.id)));
707 let interactive = column.sortable && !column.disabled && on_sort.is_some();
708 let head_focus = interactive.then(|| {
709 window
710 .use_keyed_state(
711 (ElementId::from(column.id.clone()), "table-head-focus"),
712 cx,
713 |_, cx| cx.focus_handle(),
714 )
715 .read(cx)
716 .clone()
717 });
718 let head_feedback = ripple_state(&head_id, interactive, window, cx);
719 let head_interaction = head_focus.as_ref().map_or_else(
720 || {
721 let mut state = InteractionState::default();
722 state.disabled = column.disabled;
723 state
724 },
725 |focus| head_feedback.borrow().interaction(true, focus, window),
726 );
727 let head_text_color = if column.disabled {
728 colors.disabled_content
729 } else {
730 colors.header_content
731 };
732
733 let next_dir = SortDirection::next_from(column.sort_direction);
734 let col_id = column.id.clone();
735 let trigger_sort = on_sort.clone().filter(|_| interactive).map(|handler| {
736 let action: RowActivateHandler = Rc::new(ThemeScope::bind_action(
737 move |window, cx| handler(&col_id, next_dir, window, cx),
738 window,
739 cx,
740 ));
741 action
742 });
743
744 let sort_icon = column.sort_direction.map(|dir| {
745 let mut icon = Icon::new(IconName::ArrowDropDown)
746 .size(px(18.))
747 .color_override(if column.disabled {
748 colors.disabled_content
749 } else {
750 colors.sort_indicator
751 });
752 if dir == SortDirection::Ascending {
753 icon = icon.rotate(radians(PI));
754 }
755 icon
756 });
757
758 let label_text = Text::new(column.label.clone())
759 .role(TypeRole::LabelLarge)
760 .emphasized(column.sort_direction.is_some())
761 .color_override(head_text_color)
762 .max_lines(1);
763
764 let head = TableHead::new(head_id, col_ix + 1)
765 .relative()
766 .flex()
767 .when(rtl, Styled::flex_row_reverse)
768 .items_center()
769 .gap_1()
770 .min_h(header_height)
771 .pt(padding.top)
772 .pb(padding.bottom)
773 .pl(padding.left)
774 .pr(padding.right)
775 .overflow_hidden()
776 .aria_label(column.label.clone())
777 .when(interactive, |el| el.cursor(CursorStyle::PointingHand));
778 let head = apply_column_sizing(head, column);
779 let head = apply_cell_alignment(head, column.alignment);
780
781 let head = if let (Some(focus), Some(trigger)) = (head_focus, trigger_sort) {
782 let click_feedback = head_feedback.clone();
783 let click_focus = focus.clone();
784 let click_trigger = trigger.clone();
785 let a11y_trigger = trigger;
786 let head = feedback_target(
787 head.track_focus(&focus)
788 .tab_stop(true)
789 .on_click(move |event: &ClickEvent, window, cx| {
790 if click_feedback.borrow().blocks_activation(event) {
791 return;
792 }
793 click_focus.focus(window, cx);
794 activate_feedback(event, &click_feedback, window, cx);
795 cx.stop_propagation();
796 click_trigger(window, cx);
797 })
798 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
799 a11y_trigger(window, cx);
800 }),
801 head_feedback.clone(),
802 true,
803 Some(focus),
804 );
805 head.child(render_feedback_overlay(
806 head_feedback,
807 head_interaction,
808 head_text_color,
809 colors.focus_ring,
810 direction,
811 reduced_motion,
812 ))
813 } else {
814 head
815 };
816
817 header_cells.push(head.child(label_text).children(sort_icon));
818 }
819
820 let row_count = self.rows.len();
821 let mut body_rows = Vec::with_capacity(row_count);
822 for (row_ix, row) in self.rows.into_iter().enumerate() {
823 let row_id_str = row.id.clone();
824 let row_elem_id = ElementId::from((self.id.clone(), format!("row-{}", row.id)));
825 let row_label = row_default_label(&row);
826 let is_selected = row.selected;
827 let is_disabled = row.disabled;
828 let interactive = row_enabled[row_ix];
829 let focus = row_focus[row_ix].clone();
830 let is_tab_stop = Some(row_ix) == row_tab_stop;
831
832 let row_feedback = ripple_state(&row_elem_id, interactive, window, cx);
833 let row_interaction = if interactive {
834 row_feedback.borrow().interaction(true, &focus, window)
835 } else {
836 let mut state = InteractionState::default();
837 state.disabled = is_disabled;
838 state
839 };
840
841 let row_bg = if is_selected {
842 colors.selected_row_container
843 } else if self.striped && row_ix % 2 == 1 {
844 colors.striped_row_container
845 } else {
846 colors.row_container
847 };
848 let row_fg = if is_disabled {
849 colors.disabled_content
850 } else if is_selected {
851 colors.selected_row_content
852 } else {
853 colors.row_content
854 };
855
856 let row_activate = row.on_activate;
857 let trigger_row = interactive.then(|| {
858 let on_select = on_row_select.clone();
859 let row_id = row_id_str.clone();
860 let action: RowActivateHandler = Rc::new(ThemeScope::bind_action(
861 move |window, cx| {
862 if let Some(on_select) = &on_select {
863 on_select(&row_id, window, cx);
864 }
865 if let Some(activate) = &row_activate {
866 activate(window, cx);
867 }
868 },
869 window,
870 cx,
871 ));
872 action
873 });
874
875 let mut cell_elements = Vec::with_capacity(self.columns.len());
876 let mut cells_iter = row.cells.into_iter();
877 for (col_ix, column) in self.columns.iter().enumerate() {
878 let cell_id =
879 ElementId::from((row_elem_id.clone(), format!("cell-{}", column.id)));
880 let cell = cells_iter.next();
881 let alignment = cell
882 .as_ref()
883 .and_then(|c| c.alignment)
884 .unwrap_or(column.alignment);
885 let cell_content = match cell {
886 Some(cell) => match cell.content {
887 CellContent::Text(text) => {
888 let text_color = if is_disabled {
889 colors.disabled_content
890 } else if is_selected {
891 colors.selected_row_content
892 } else if cell.muted {
893 colors.muted_content
894 } else {
895 colors.row_content
896 };
897 Text::new(text)
898 .role(TypeRole::BodyMedium)
899 .color_override(text_color)
900 .max_lines(1)
901 .into_any_element()
902 }
903 CellContent::Custom(el) => el,
904 },
905 None => div().into_any_element(),
906 };
907
908 let cell_el = TableCell::new(cell_id, col_ix + 1)
909 .flex()
910 .when(rtl, Styled::flex_row_reverse)
911 .items_center()
912 .min_h(row_height)
913 .pt(padding.top)
914 .pb(padding.bottom)
915 .pl(padding.left)
916 .pr(padding.right)
917 .overflow_hidden()
918 .child(cell_content);
919 let cell_el = apply_column_sizing(cell_el, column);
920 let cell_el = apply_cell_alignment(cell_el, alignment);
921 cell_elements.push(cell_el);
922 }
923
924 let is_last = row_ix + 1 == row_count;
925 let row_el = TableRow::new(row_elem_id, row_ix + 2)
926 .relative()
927 .w_full()
928 .flex()
929 .when(rtl, Styled::flex_row_reverse)
930 .items_stretch()
931 .bg(row_bg)
932 .text_color(row_fg)
933 .aria_label(row_label)
934 .aria_selected(is_selected)
935 .when(self.show_row_dividers && !is_last, |el| {
936 el.border_b_1().border_color(colors.divider)
937 })
938 .when(interactive, |el| el.cursor(CursorStyle::PointingHand));
939
940 let row_el = if let Some(trigger) = trigger_row {
941 let click_feedback = row_feedback.clone();
942 let click_focus = focus.clone();
943 let click_trigger = trigger.clone();
944 let a11y_trigger = trigger;
945 let row_el = feedback_target(
946 row_el
947 .track_focus(&focus)
948 .tab_stop(is_tab_stop)
949 .on_click(move |event: &ClickEvent, window, cx| {
950 if click_feedback.borrow().blocks_activation(event) {
951 return;
952 }
953 click_focus.focus(window, cx);
954 activate_feedback(event, &click_feedback, window, cx);
955 cx.stop_propagation();
956 click_trigger(window, cx);
957 })
958 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
959 a11y_trigger(window, cx);
960 }),
961 row_feedback.clone(),
962 true,
963 Some(focus),
964 );
965 row_el.child(render_feedback_overlay(
966 row_feedback,
967 row_interaction,
968 row_fg,
969 colors.focus_ring,
970 direction,
971 reduced_motion,
972 ))
973 } else {
974 row_el
975 };
976
977 body_rows.push(row_el.children(cell_elements));
978 }
979
980 let nav_focus = row_focus;
981 let nav_enabled = row_enabled;
982
983 let caption_el = self.caption.map(|caption| {
984 TableCaption::new((self.id.clone(), "caption"))
985 .w_full()
986 .flex()
987 .when(rtl, Styled::flex_row_reverse)
988 .items_center()
989 .pt(padding.top)
990 .pb(padding.bottom)
991 .pl(padding.left)
992 .pr(padding.right)
993 .border_b_1()
994 .border_color(colors.divider)
995 .child(
996 Text::new(caption)
997 .role(TypeRole::LabelMedium)
998 .color_override(colors.caption)
999 .wrap(),
1000 )
1001 });
1002
1003 let header_el = (!self.columns.is_empty()).then(|| {
1004 TableHeader::new((self.id.clone(), "header"))
1005 .w_full()
1006 .bg(colors.header_container)
1007 .border_b_1()
1008 .border_color(colors.divider)
1009 .child(
1010 TableRow::new((self.id.clone(), "header-row"), 1)
1011 .w_full()
1012 .flex()
1013 .when(rtl, Styled::flex_row_reverse)
1014 .items_stretch()
1015 .children(header_cells),
1016 )
1017 });
1018
1019 let body_el = TableBody::new((self.id.clone(), "body"))
1020 .w_full()
1021 .flex()
1022 .flex_col()
1023 .on_key_down(move |event: &KeyDownEvent, window, cx| {
1024 if event.keystroke.modifiers.modified() {
1025 return;
1026 }
1027 if !nav_focus.iter().any(|handle| handle.is_focused(window)) {
1028 return;
1029 }
1030 let items: Vec<_> = nav_focus
1031 .iter()
1032 .zip(&nav_enabled)
1033 .map(|(handle, enabled)| (handle, *enabled))
1034 .collect();
1035 if move_roving_focus(
1036 &items,
1037 &event.keystroke.key,
1038 gpui::Axis::Vertical,
1039 direction,
1040 window,
1041 cx,
1042 )
1043 .is_some()
1044 {
1045 cx.stop_propagation();
1046 window.refresh();
1047 }
1048 })
1049 .children(body_rows);
1050
1051 Table::new(self.id)
1052 .row_count(total_rows)
1053 .column_count(total_columns)
1054 .when_some(self.accessible_label, |table, label| {
1055 table.accessibility_label(label)
1056 })
1057 .w_full()
1058 .flex()
1059 .flex_col()
1060 .overflow_hidden()
1061 .bg(colors.container)
1062 .border_1()
1063 .border_color(colors.border)
1064 .rounded_tl(px(radii[0]))
1065 .rounded_tr(px(radii[1]))
1066 .rounded_br(px(radii[2]))
1067 .rounded_bl(px(radii[3]))
1068 .children(caption_el)
1069 .children(header_el)
1070 .child(body_el)
1071 .refine_style(&self.style)
1072 })
1073 }
1074}
1075
1076#[cfg(test)]
1077mod tests {
1078 use super::*;
1079
1080 #[test]
1081 fn sort_direction_cycles_and_toggles() {
1082 assert_eq!(SortDirection::next_from(None), SortDirection::Ascending);
1083 assert_eq!(
1084 SortDirection::next_from(Some(SortDirection::Ascending)),
1085 SortDirection::Descending
1086 );
1087 assert_eq!(
1088 SortDirection::next_from(Some(SortDirection::Descending)),
1089 SortDirection::Ascending
1090 );
1091 assert_eq!(
1092 SortDirection::Ascending.toggled(),
1093 SortDirection::Descending
1094 );
1095 assert_eq!(
1096 SortDirection::Descending.toggled(),
1097 SortDirection::Ascending
1098 );
1099 }
1100
1101 #[test]
1102 fn density_scales_table_heights_and_respects_overrides() {
1103 let compact = table_row_height(Density::Compact, None);
1104 let standard = table_row_height(Density::Standard, None);
1105 let comfortable = table_row_height(Density::Comfortable, None);
1106 assert!(compact < standard);
1107 assert!(standard < comfortable);
1108 assert_eq!(table_row_height(Density::Compact, Some(px(64.))), px(64.));
1109 assert_eq!(
1110 table_header_height(Density::Standard, Some(px(40.))),
1111 px(40.)
1112 );
1113 }
1114
1115 #[test]
1116 fn column_sanitizes_invalid_dimensions_and_sort_direction_implies_sortable() {
1117 let col = DataTableColumn::new("name", "Name")
1118 .width(px(-10.))
1119 .min_width(px(f32::NAN))
1120 .weight(-2.0)
1121 .sort_direction(Some(SortDirection::Ascending));
1122 assert_eq!(col.width, None);
1123 assert_eq!(col.min_width, None);
1124 assert_eq!(col.weight, 1.0);
1125 assert!(col.sortable);
1126 assert_eq!(col.sort_direction, Some(SortDirection::Ascending));
1127 }
1128}