1use gpui_base::TestSupportExt as _;
2use std::{ops::Range, rc::Rc, time::Duration};
3
4use crate::{
5 ActiveTheme, ElementExt, Icon, IconName, StyleSized as _, StyledExt, VirtualListScrollHandle,
6 actions::{
7 Cancel, SelectDown, SelectFirst, SelectLast, SelectNextColumn, SelectPageDown,
8 SelectPageUp, SelectPrevColumn, SelectUp,
9 },
10 h_flex,
11 menu::{ContextMenuExt, PopupMenu},
12 scroll::{ScrollableMask, Scrollbar},
13 v_flex,
14};
15use gpui::{
16 AppContext, Axis, Bounds, ClickEvent, Context, Div, DragMoveEvent, ElementId, EventEmitter,
17 FocusHandle, Focusable, InteractiveElement, IntoElement, ListSizingBehavior, MouseButton,
18 MouseDownEvent, ParentElement, Pixels, Point, Render, ScrollStrategy, SharedString, Stateful,
19 StatefulInteractiveElement as _, Styled, Task, TextAlign, UniformListScrollHandle, Window, div,
20 prelude::FluentBuilder, px, uniform_list,
21};
22use rust_i18n::t;
23
24use super::*;
25
26const HANDLE_PADDING: Pixels = px(4.);
32
33#[derive(Copy, Clone, Debug, PartialEq, Eq)]
34enum SelectionMode {
35 Column,
36 Row,
37 Cell,
38}
39
40impl SelectionMode {
41 #[inline(always)]
42 fn is_row(&self) -> bool {
43 matches!(self, SelectionMode::Row)
44 }
45
46 #[inline(always)]
47 fn is_column(&self) -> bool {
48 matches!(self, SelectionMode::Column)
49 }
50
51 #[inline(always)]
52 fn is_cell(&self) -> bool {
53 matches!(self, SelectionMode::Cell)
54 }
55}
56
57#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
64pub enum TableSelection {
65 #[default]
67 None,
68 Row(usize),
70 Column(usize),
72 Cell(usize, usize),
74}
75
76#[derive(Clone)]
78pub enum TableEvent {
79 SelectRow(usize),
81 DoubleClickedRow(usize),
83 SelectColumn(usize),
85 SelectCell(usize, usize),
92 DoubleClickedCell(usize, usize),
99 ColumnWidthsChanged(Vec<Pixels>),
103 MoveColumn(usize, usize),
108 RightClickedRow(Option<usize>),
113 RightClickedCell(usize, usize),
121 ClearSelection,
125}
126
127#[derive(Debug, Default)]
129pub struct TableVisibleRange {
130 rows: Range<usize>,
132 cols: Range<usize>,
134}
135
136impl TableVisibleRange {
137 pub fn rows(&self) -> &Range<usize> {
139 &self.rows
140 }
141
142 pub fn cols(&self) -> &Range<usize> {
144 &self.cols
145 }
146}
147
148#[derive(Clone, Copy)]
151struct ResizeOrigin {
152 x: Pixels,
153 width: Pixels,
154}
155
156#[derive(Clone)]
206pub(crate) struct HeaderCell {
207 pub label: SharedString,
208 pub width: Pixels,
209 col_span: usize,
210 is_leaf: bool,
211 leaf_col_ix: Option<usize>,
212 start_leaf_col_ix: usize,
213}
214
215pub struct TableState<D: TableDelegate> {
216 focus_handle: FocusHandle,
217 delegate: D,
218 pub(super) options: TableOptions,
219 bounds: Bounds<Pixels>,
221 fixed_head_cols_bounds: Bounds<Pixels>,
223 fixed_right_head_cols_bounds: Bounds<Pixels>,
225
226 col_groups: Vec<ColGroup>,
227 header_layout: Vec<Vec<HeaderCell>>,
228
229 pub loop_selection: bool,
233 pub col_selectable: bool,
235 pub row_selectable: bool,
237 select_on_modifier_click: bool,
248 pub cell_selectable: bool,
257 pub row_header: bool,
266 pub sortable: bool,
268 pub col_resizable: bool,
270 pub col_movable: bool,
272 pub col_fixed: bool,
274
275 pub vertical_scroll_handle: UniformListScrollHandle,
276 pub horizontal_scroll_handle: VirtualListScrollHandle,
277
278 selected_row: Option<usize>,
279 selection_mode: SelectionMode,
280 right_clicked_row: Option<usize>,
281 right_clicked_cell: Option<(usize, usize)>,
282 selected_col: Option<usize>,
283 selected_cell: Option<(usize, usize)>,
284
285 resizing_col: Option<usize>,
287 resize_origin: Option<ResizeOrigin>,
289 fitted_col: Option<usize>,
295
296 col_drag_gap: Option<usize>,
300
301 visible_range: TableVisibleRange,
303
304 _measure: Vec<Duration>,
305 _load_more_task: Task<()>,
306}
307
308impl<D> TableState<D>
309where
310 D: TableDelegate,
311{
312 pub fn new(delegate: D, _: &mut Window, cx: &mut Context<Self>) -> Self {
314 let mut this = Self {
315 focus_handle: cx.focus_handle().tab_stop(true),
316 options: TableOptions::default(),
317 delegate,
318 col_groups: Vec::new(),
319 header_layout: Vec::new(),
320 horizontal_scroll_handle: VirtualListScrollHandle::new(),
321 vertical_scroll_handle: UniformListScrollHandle::new(),
322 selection_mode: SelectionMode::Row,
323 selected_row: None,
324 right_clicked_row: None,
325 right_clicked_cell: None,
326 selected_col: None,
327 selected_cell: None,
328 resizing_col: None,
329 resize_origin: None,
330 fitted_col: None,
331 col_drag_gap: None,
332 bounds: Bounds::default(),
333 fixed_head_cols_bounds: Bounds::default(),
334 fixed_right_head_cols_bounds: Bounds::default(),
335 visible_range: TableVisibleRange::default(),
336 loop_selection: true,
337 col_selectable: true,
338 row_selectable: true,
339 select_on_modifier_click: true,
340 cell_selectable: false,
341 row_header: true,
342 sortable: true,
343 col_movable: true,
344 col_resizable: true,
345 col_fixed: true,
346 _load_more_task: Task::ready(()),
347 _measure: Vec::new(),
348 };
349
350 this.prepare_col_groups(cx);
351 this
352 }
353
354 pub fn delegate(&self) -> &D {
356 &self.delegate
357 }
358
359 pub fn delegate_mut(&mut self) -> &mut D {
361 &mut self.delegate
362 }
363
364 pub fn loop_selection(mut self, loop_selection: bool) -> Self {
366 self.loop_selection = loop_selection;
367 self
368 }
369
370 pub fn col_movable(mut self, col_movable: bool) -> Self {
372 self.col_movable = col_movable;
373 self
374 }
375
376 pub fn col_resizable(mut self, col_resizable: bool) -> Self {
378 self.col_resizable = col_resizable;
379 self
380 }
381
382 pub fn sortable(mut self, sortable: bool) -> Self {
384 self.sortable = sortable;
385 self
386 }
387
388 pub fn row_selectable(mut self, row_selectable: bool) -> Self {
390 self.row_selectable = row_selectable;
391 self
392 }
393
394 pub fn select_on_modifier_click(mut self, select_on_modifier_click: bool) -> Self {
397 self.select_on_modifier_click = select_on_modifier_click;
398 self
399 }
400
401 pub fn col_selectable(mut self, col_selectable: bool) -> Self {
403 self.col_selectable = col_selectable;
404 self
405 }
406
407 pub fn cell_selectable(mut self, cell_selectable: bool) -> Self {
425 self.cell_selectable = cell_selectable;
426 self
427 }
428
429 pub fn row_header(mut self, row_header: bool) -> Self {
440 self.row_header = row_header;
441 self
442 }
443
444 pub fn refresh(&mut self, cx: &mut Context<Self>) {
446 self.prepare_col_groups(cx);
447 }
448
449 pub fn scroll_to_row(&mut self, row_ix: usize, cx: &mut Context<Self>) {
451 self.vertical_scroll_handle
452 .scroll_to_item(row_ix, ScrollStrategy::Top);
453 cx.notify();
454 }
455
456 pub fn scroll_to_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
458 let scrollable_cols = self.scrollable_cols();
459 if col_ix >= scrollable_cols.end {
461 return;
462 }
463 let col_ix = col_ix.saturating_sub(scrollable_cols.start);
464
465 match self.horizontal_offset_for_col(col_ix) {
473 Some(offset_x) => {
474 let mut offset = self.horizontal_scroll_handle.offset();
475 offset.x = offset_x;
476 self.horizontal_scroll_handle.set_offset(offset);
477 }
478 None => self
481 .horizontal_scroll_handle
482 .scroll_to_item(col_ix, ScrollStrategy::Top),
483 }
484
485 cx.notify();
486 }
487
488 fn horizontal_offset_for_col(&self, col_ix: usize) -> Option<Pixels> {
500 let viewport_width = self.horizontal_scroll_handle.bounds().size.width;
501 if viewport_width <= px(0.) {
502 return None;
503 }
504
505 let cols = self.col_groups.get(self.scrollable_cols())?;
506 let col_left: Pixels = cols.get(..col_ix)?.iter().map(|col| col.width).sum();
507 let col_right = col_left + cols.get(col_ix)?.width;
508 let offset_x = self.horizontal_scroll_handle.offset().x;
509
510 Some(if col_left + offset_x < px(0.) {
511 -col_left
512 } else if col_right + offset_x > viewport_width {
513 viewport_width - col_right
514 } else {
515 offset_x
516 })
517 }
518
519 pub fn selection(&self) -> TableSelection {
524 if let Some(row_ix) = self.selected_row() {
525 TableSelection::Row(row_ix)
526 } else if let Some(col_ix) = self.selected_col() {
527 TableSelection::Column(col_ix)
528 } else if let Some((row_ix, col_ix)) = self.selected_cell() {
529 TableSelection::Cell(row_ix, col_ix)
530 } else {
531 TableSelection::None
532 }
533 }
534
535 pub fn selected_row(&self) -> Option<usize> {
540 self.selected_row.filter(|_| self.selection_mode.is_row())
541 }
542
543 pub fn set_selected_row(&mut self, row_ix: usize, cx: &mut Context<Self>) {
548 self.select_row(row_ix, false, cx);
549 }
550
551 pub(super) fn select_row(&mut self, row_ix: usize, scroll: bool, cx: &mut Context<Self>) {
552 let is_down = match self.selected_row {
553 Some(selected_row) => row_ix > selected_row,
554 None => true,
555 };
556
557 self.selection_mode = SelectionMode::Row;
558 self.right_clicked_row = None;
559 self.selected_row = Some(row_ix);
560 if scroll {
561 self.vertical_scroll_handle.scroll_to_item(
562 row_ix,
563 if is_down {
564 ScrollStrategy::Bottom
565 } else {
566 ScrollStrategy::Top
567 },
568 );
569 }
570 cx.emit(TableEvent::SelectRow(row_ix));
571 cx.emit(TableEvent::RightClickedRow(None));
572 cx.notify();
573 }
574
575 pub fn right_clicked_row(&self) -> Option<usize> {
577 self.right_clicked_row
578 }
579
580 pub fn right_clicked_cell(&self) -> Option<(usize, usize)> {
582 self.right_clicked_cell
583 }
584
585 pub fn set_right_clicked_row(&mut self, row: Option<usize>, cx: &mut Context<Self>) {
590 self.right_clicked_row = row;
591 cx.notify();
592 }
593
594 pub fn selected_col(&self) -> Option<usize> {
599 self.selected_col
600 .filter(|_| self.selection_mode.is_column())
601 }
602
603 pub fn set_selected_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
608 self.select_col(col_ix, false, cx);
609 }
610
611 fn select_col(&mut self, col_ix: usize, scroll: bool, cx: &mut Context<Self>) {
612 self.selection_mode = SelectionMode::Column;
613 self.selected_col = Some(col_ix);
614 if scroll {
615 self.scroll_to_col(col_ix, cx);
616 }
617 cx.emit(TableEvent::SelectColumn(col_ix));
618 cx.notify();
619 }
620
621 pub fn selected_cell(&self) -> Option<(usize, usize)> {
633 self.selected_cell.filter(|_| self.selection_mode.is_cell())
634 }
635
636 pub fn set_selected_cell(&mut self, row_ix: usize, col_ix: usize, cx: &mut Context<Self>) {
653 self.select_cell(row_ix, col_ix, false, cx);
654 }
655
656 fn select_cell(&mut self, row_ix: usize, col_ix: usize, scroll: bool, cx: &mut Context<Self>) {
657 self.selection_mode = SelectionMode::Cell;
658 self.selected_cell = Some((row_ix, col_ix));
659 self.right_clicked_cell = None;
660
661 if scroll {
662 self.vertical_scroll_handle
663 .scroll_to_item(row_ix, ScrollStrategy::Center);
664 self.scroll_to_col(col_ix, cx);
665 }
666
667 cx.emit(TableEvent::SelectCell(row_ix, col_ix));
668 cx.notify();
669 }
670
671 pub fn set_selection(&mut self, selection: TableSelection, cx: &mut Context<Self>) {
676 match selection {
677 TableSelection::None => self.clear_selection(cx),
678 TableSelection::Row(row_ix) => self.set_selected_row(row_ix, cx),
679 TableSelection::Column(col_ix) => self.set_selected_col(col_ix, cx),
680 TableSelection::Cell(row_ix, col_ix) => self.set_selected_cell(row_ix, col_ix, cx),
681 }
682 }
683
684 pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
686 self.selection_mode = SelectionMode::Row;
687 self.selected_row = None;
688 self.selected_col = None;
689 self.selected_cell = None;
690 cx.emit(TableEvent::ClearSelection);
691 cx.notify();
692 }
693
694 pub fn visible_range(&self) -> &TableVisibleRange {
698 &self.visible_range
699 }
700
701 pub fn headers(&self, cx: &App) -> Vec<String> {
706 let columns_count = self.delegate.columns_count(cx);
707 let mut headers = Vec::with_capacity(columns_count);
708 for col_ix in 0..columns_count {
709 let column = self.delegate.column(col_ix, cx);
710 headers.push(column.name.to_string());
711 }
712
713 headers
714 }
715
716 pub fn dump(&self, cx: &App) -> (Vec<String>, Vec<Vec<String>>) {
723 self.dump_range(0..self.delegate.rows_count(cx), cx)
724 }
725
726 pub fn dump_range(&self, range: Range<usize>, cx: &App) -> (Vec<String>, Vec<Vec<String>>) {
734 let columns_count = self.delegate.columns_count(cx);
735 let rows_count = self.delegate.rows_count(cx);
736 let start = range.start.min(rows_count);
737 let end = range.end.min(rows_count).max(start);
738
739 let mut rows = Vec::with_capacity(end - start);
740 for row_ix in start..end {
741 let mut row = Vec::with_capacity(columns_count);
742 for col_ix in 0..columns_count {
743 row.push(self.delegate.cell_text(row_ix, col_ix, cx));
744 }
745 rows.push(row);
746 }
747
748 (self.headers(cx), rows)
749 }
750
751 pub fn refresh_header_layout(&mut self, cx: &mut Context<Self>) {
755 self.update_header_layout(cx);
756 cx.notify();
757 }
758
759 fn prepare_col_groups(&mut self, cx: &mut Context<Self>) {
760 self.col_groups = (0..self.delegate.columns_count(cx))
761 .map(|col_ix| {
762 let column = self.delegate().column(col_ix, cx);
763 ColGroup {
764 width: column.width,
765 bounds: Bounds::default(),
766 column,
767 }
768 })
769 .collect();
770
771 self.update_header_layout(cx);
772 }
773
774 fn update_header_layout(&mut self, cx: &mut Context<Self>) {
775 let group_rows = self.delegate.group_headers(cx);
776
777 let mut layout = match group_rows.as_ref() {
778 Some(rows) => Vec::with_capacity(rows.len() + 1),
779 None => Vec::with_capacity(1),
780 };
781
782 if let Some(group_rows) = group_rows {
783 for row in group_rows {
784 let mut cell_row = Vec::with_capacity(row.len());
785 let mut current_leaf_ix = 0;
786 for group in row {
787 let mut width = px(0.);
788 let start_leaf_col_ix = current_leaf_ix;
789 for i in 0..group.span {
790 if current_leaf_ix + i < self.col_groups.len() {
791 width += self.col_groups[current_leaf_ix + i].width;
792 }
793 }
794 current_leaf_ix += group.span;
795 cell_row.push(HeaderCell {
796 label: group.label.clone(),
797 width,
798 col_span: group.span,
799 is_leaf: false,
800 leaf_col_ix: None,
801 start_leaf_col_ix,
802 });
803 }
804 layout.push(cell_row);
805 }
806 }
807
808 let mut leaf_row = Vec::with_capacity(self.col_groups.len());
809 for (ix, group) in self.col_groups.iter().enumerate() {
810 leaf_row.push(HeaderCell {
811 label: group.column.name.clone(),
812 width: group.width,
813 col_span: 1,
814 is_leaf: true,
815 leaf_col_ix: Some(ix),
816 start_leaf_col_ix: ix,
817 });
818 }
819 layout.push(leaf_row);
820
821 self.header_layout = layout;
822 }
823
824 fn fixed_cols_count(&self, side: ColumnFixed) -> usize {
825 if !self.col_fixed {
826 return 0;
827 }
828
829 self.col_groups
830 .iter()
831 .filter(|col| col.column.fixed == Some(side))
832 .count()
833 }
834
835 fn scrollable_cols(&self) -> Range<usize> {
841 let total = self.col_groups.len();
842 let left = self.fixed_cols_count(ColumnFixed::Left).min(total);
843 let right = self.fixed_cols_count(ColumnFixed::Right).min(total - left);
844 left..total - right
845 }
846
847 fn col_fixed_side(&self, col_ix: usize) -> Option<ColumnFixed> {
849 let scrollable_cols = self.scrollable_cols();
850 if col_ix < scrollable_cols.start {
851 Some(ColumnFixed::Left)
852 } else if col_ix >= scrollable_cols.end {
853 Some(ColumnFixed::Right)
854 } else {
855 None
856 }
857 }
858
859 fn header_row_height(&self) -> Pixels {
861 self.options
862 .header_row_height
863 .unwrap_or(self.options.size.table_row_height())
864 }
865
866 fn header_band_height(&self) -> Pixels {
869 self.header_row_height() * self.header_layout.len().max(1) as f32
870 }
871
872 fn page_item_count(&self) -> usize {
873 let row_height = self.options.size.table_row_height();
874 let body_height = (self.bounds.size.height - self.header_band_height()).max(px(0.));
875 let count = (body_height / row_height).floor() as usize;
876 count.max(1)
877 }
878
879 fn on_row_right_click(
880 &mut self,
881 _: &MouseDownEvent,
882 row_ix: Option<usize>,
883 _: &mut Window,
884 cx: &mut Context<Self>,
885 ) {
886 self.right_clicked_row = row_ix;
887 self.right_clicked_cell = None;
888 cx.emit(TableEvent::RightClickedRow(row_ix));
889 }
890
891 fn on_cell_right_click(
892 &mut self,
893 _: &MouseDownEvent,
894 row_ix: usize,
895 col_ix: usize,
896 _: &mut Window,
897 cx: &mut Context<Self>,
898 ) {
899 if !self.cell_selectable {
900 return;
901 }
902
903 cx.stop_propagation();
904 self.right_clicked_cell = Some((row_ix, col_ix));
905 self.right_clicked_row = None;
906 cx.emit(TableEvent::RightClickedCell(row_ix, col_ix));
907 }
908
909 fn on_row_left_click(
910 &mut self,
911 e: &ClickEvent,
912 row_ix: usize,
913 _: &mut Window,
914 cx: &mut Context<Self>,
915 ) {
916 if !self.row_selectable {
917 return;
918 }
919
920 cx.stop_propagation();
921 if self.selects_row_on_click(e, cx) {
922 self.select_row(row_ix, true, cx);
923 }
924
925 if e.click_count() == 2 {
926 cx.emit(TableEvent::DoubleClickedRow(row_ix));
927 }
928 }
929
930 fn selects_row_on_click(&self, e: &ClickEvent, cx: &App) -> bool {
932 let modifiers = e.modifiers();
933 self.select_on_modifier_click || !(modifiers.secondary(cx) || modifiers.shift)
934 }
935
936 fn on_col_head_click(&mut self, col_ix: usize, _: &mut Window, cx: &mut Context<Self>) {
937 if !self.col_selectable {
938 return;
939 }
940
941 let Some(col_group) = self.col_groups.get(col_ix) else {
942 return;
943 };
944
945 if !col_group.column.selectable {
946 return;
947 }
948
949 self.select_col(col_ix, true, cx)
950 }
951
952 fn on_cell_click(
953 &mut self,
954 e: &ClickEvent,
955 row_ix: usize,
956 col_ix: usize,
957 _: &mut Window,
958 cx: &mut Context<Self>,
959 ) {
960 if !self.cell_selectable {
961 return;
962 }
963
964 cx.stop_propagation();
965
966 let is_double_click = e.click_count() == 2;
967
968 let is_reselect = self.selected_cell() == Some((row_ix, col_ix));
974 let should_escalate_to_row = !self.row_header
975 && self.row_selectable
976 && is_reselect
977 && !is_double_click
978 && self.selects_row_on_click(e, cx);
979 if should_escalate_to_row {
980 self.select_row(row_ix, true, cx);
981 return;
982 }
983
984 self.select_cell(row_ix, col_ix, true, cx);
985
986 if is_double_click {
987 cx.emit(TableEvent::DoubleClickedCell(row_ix, col_ix));
988 }
989 }
990
991 fn has_selection(&self) -> bool {
992 self.selection() != TableSelection::None
993 }
994
995 pub(super) fn action_cancel(&mut self, _: &Cancel, _: &mut Window, cx: &mut Context<Self>) {
996 if self.has_selection() {
997 self.clear_selection(cx);
998 return;
999 }
1000 cx.propagate();
1001 }
1002
1003 pub(super) fn action_select_prev(
1004 &mut self,
1005 _: &SelectUp,
1006 _: &mut Window,
1007 cx: &mut Context<Self>,
1008 ) {
1009 let rows_count = self.delegate.rows_count(cx);
1010 if rows_count < 1 {
1011 return;
1012 }
1013
1014 if self.selection_mode.is_cell() {
1016 if let Some((row_ix, col_ix)) = self.selected_cell {
1017 let new_row = if row_ix > 0 {
1018 row_ix.saturating_sub(1)
1019 } else if self.loop_selection {
1020 rows_count.saturating_sub(1)
1021 } else {
1022 row_ix
1023 };
1024 self.select_cell(new_row, col_ix, true, cx);
1025 } else {
1026 self.select_cell(0, 0, true, cx);
1028 }
1029 return;
1030 }
1031
1032 if !self.row_selectable {
1034 return;
1035 }
1036 let mut selected_row = self.selected_row.unwrap_or(0);
1037 if selected_row > 0 {
1038 selected_row = selected_row.saturating_sub(1);
1039 } else {
1040 if self.loop_selection {
1041 selected_row = rows_count.saturating_sub(1);
1042 }
1043 }
1044
1045 self.select_row(selected_row, true, cx);
1046 }
1047
1048 pub(super) fn action_select_next(
1049 &mut self,
1050 _: &SelectDown,
1051 _: &mut Window,
1052 cx: &mut Context<Self>,
1053 ) {
1054 let rows_count = self.delegate.rows_count(cx);
1055 if rows_count < 1 {
1056 return;
1057 }
1058
1059 if self.selection_mode.is_cell() {
1061 if let Some((row_ix, col_ix)) = self.selected_cell {
1062 let new_row = if row_ix < rows_count.saturating_sub(1) {
1063 row_ix + 1
1064 } else if self.loop_selection {
1065 0
1066 } else {
1067 row_ix
1068 };
1069 self.select_cell(new_row, col_ix, true, cx);
1070 } else {
1071 self.select_cell(0, 0, true, cx);
1073 }
1074 return;
1075 }
1076
1077 if !self.row_selectable {
1079 return;
1080 }
1081 let selected_row = match self.selected_row {
1082 Some(selected_row) if selected_row < rows_count.saturating_sub(1) => selected_row + 1,
1083 Some(selected_row) => {
1084 if self.loop_selection {
1085 0
1086 } else {
1087 selected_row
1088 }
1089 }
1090 _ => 0,
1091 };
1092
1093 self.select_row(selected_row, true, cx);
1094 }
1095
1096 pub(super) fn action_select_first_column(
1097 &mut self,
1098 _: &SelectFirst,
1099 _: &mut Window,
1100 cx: &mut Context<Self>,
1101 ) {
1102 if self.selection_mode.is_cell() {
1104 if let Some((row_ix, _)) = self.selected_cell {
1105 self.select_cell(row_ix, 0, true, cx);
1106 } else {
1107 self.select_cell(0, 0, true, cx);
1109 }
1110 return;
1111 }
1112
1113 if self.selection_mode.is_row() && self.row_selectable {
1115 if self.delegate.rows_count(cx) > 0 {
1116 self.select_row(0, true, cx);
1117 }
1118 return;
1119 }
1120
1121 self.select_col(0, true, cx);
1123 }
1124
1125 pub(super) fn action_select_last_column(
1126 &mut self,
1127 _: &SelectLast,
1128 _: &mut Window,
1129 cx: &mut Context<Self>,
1130 ) {
1131 let columns_count = self.delegate.columns_count(cx);
1132
1133 if self.selection_mode.is_cell() {
1135 if let Some((row_ix, _)) = self.selected_cell {
1136 self.select_cell(row_ix, columns_count.saturating_sub(1), true, cx);
1137 } else {
1138 self.select_cell(0, columns_count.saturating_sub(1), true, cx);
1140 }
1141 return;
1142 }
1143
1144 if self.selection_mode.is_row() && self.row_selectable {
1146 let rows_count = self.delegate.rows_count(cx);
1147 if rows_count > 0 {
1148 self.select_row(rows_count - 1, true, cx);
1149 }
1150 return;
1151 }
1152
1153 self.select_col(columns_count.saturating_sub(1), true, cx);
1155 }
1156
1157 pub(super) fn action_select_page_up(
1158 &mut self,
1159 _: &SelectPageUp,
1160 _: &mut Window,
1161 cx: &mut Context<Self>,
1162 ) {
1163 let step = self.page_item_count();
1164
1165 if self.selection_mode.is_cell() {
1167 if let Some((row_ix, col_ix)) = self.selected_cell {
1168 let target = row_ix.saturating_sub(step);
1169 self.select_cell(target, col_ix, true, cx);
1170 } else {
1171 self.select_cell(0, 0, true, cx);
1173 }
1174 return;
1175 }
1176
1177 if !self.row_selectable {
1179 return;
1180 }
1181 let current = self.selected_row.unwrap_or(0);
1182 let target = current.saturating_sub(step);
1183 self.select_row(target, true, cx);
1184 }
1185
1186 pub(super) fn action_select_page_down(
1187 &mut self,
1188 _: &SelectPageDown,
1189 _: &mut Window,
1190 cx: &mut Context<Self>,
1191 ) {
1192 let rows_count = self.delegate.rows_count(cx);
1193 if rows_count == 0 {
1194 return;
1195 }
1196
1197 let step = self.page_item_count();
1198
1199 if self.selection_mode.is_cell() {
1201 if let Some((row_ix, col_ix)) = self.selected_cell {
1202 let max_row = rows_count.saturating_sub(1);
1203 let target = (row_ix + step).min(max_row);
1204 self.select_cell(target, col_ix, true, cx);
1205 } else {
1206 self.select_cell(0, 0, true, cx);
1208 }
1209 return;
1210 }
1211
1212 if !self.row_selectable {
1214 return;
1215 }
1216 let current = self.selected_row.unwrap_or(0);
1217 let max_row = rows_count.saturating_sub(1);
1218 let target = (current + step).min(max_row);
1219 self.select_row(target, true, cx);
1220 }
1221
1222 pub(super) fn action_select_prev_col(
1223 &mut self,
1224 _: &SelectPrevColumn,
1225 _: &mut Window,
1226 cx: &mut Context<Self>,
1227 ) {
1228 let columns_count = self.delegate.columns_count(cx);
1229
1230 if self.selection_mode.is_cell() {
1232 if let Some((row_ix, col_ix)) = self.selected_cell {
1233 let new_col = if col_ix > 0 {
1234 col_ix.saturating_sub(1)
1235 } else if self.loop_selection {
1236 columns_count.saturating_sub(1)
1237 } else {
1238 col_ix
1239 };
1240 self.select_cell(row_ix, new_col, true, cx);
1241 } else {
1242 self.select_cell(0, 0, true, cx);
1244 }
1245 return;
1246 }
1247
1248 let mut selected_col = self.selected_col.unwrap_or(0);
1250 if selected_col > 0 {
1251 selected_col = selected_col.saturating_sub(1);
1252 } else {
1253 if self.loop_selection {
1254 selected_col = columns_count.saturating_sub(1);
1255 }
1256 }
1257 self.select_col(selected_col, true, cx);
1258 }
1259
1260 pub(super) fn action_select_next_col(
1261 &mut self,
1262 _: &SelectNextColumn,
1263 _: &mut Window,
1264 cx: &mut Context<Self>,
1265 ) {
1266 let columns_count = self.delegate.columns_count(cx);
1267
1268 if self.selection_mode.is_cell() {
1270 if let Some((row_ix, col_ix)) = self.selected_cell {
1271 let new_col = if col_ix < columns_count.saturating_sub(1) {
1272 col_ix + 1
1273 } else if self.loop_selection {
1274 0
1275 } else {
1276 col_ix
1277 };
1278 self.select_cell(row_ix, new_col, true, cx);
1279 } else {
1280 self.select_cell(0, 0, true, cx);
1282 }
1283 return;
1284 }
1285
1286 let mut selected_col = self.selected_col.unwrap_or(0);
1288 if selected_col < columns_count.saturating_sub(1) {
1289 selected_col += 1;
1290 } else {
1291 if self.loop_selection {
1292 selected_col = 0;
1293 }
1294 }
1295
1296 self.select_col(selected_col, true, cx);
1297 }
1298
1299 fn scroll_table_by_col_resizing(
1301 &mut self,
1302 mouse_position: Point<Pixels>,
1303 col_group: &ColGroup,
1304 ) {
1305 if mouse_position.x > self.bounds.right() {
1307 return;
1308 }
1309
1310 let mut offset = self.horizontal_scroll_handle.offset();
1311 let col_bounds = col_group.bounds;
1312
1313 if mouse_position.x < self.bounds.left()
1314 && col_bounds.right() < self.bounds.left() + px(20.)
1315 {
1316 offset.x += px(1.);
1317 } else if mouse_position.x > self.bounds.right()
1318 && col_bounds.right() > self.bounds.right() - px(20.)
1319 {
1320 offset.x -= px(1.);
1321 }
1322
1323 self.horizontal_scroll_handle.set_offset(offset);
1324 }
1325
1326 pub fn col_width(&self, col_ix: usize) -> Option<Pixels> {
1333 self.col_groups.get(col_ix).map(|group| group.width)
1334 }
1335
1336 pub fn fit_col(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) -> bool {
1345 if !self.is_col_resizable(col_ix) {
1346 return false;
1347 }
1348 let Some(content) = self.delegate.fit_column(col_ix, window, cx) else {
1349 return false;
1350 };
1351 let padding = self
1352 .col_groups
1353 .get(col_ix)
1354 .and_then(|group| group.column.paddings)
1355 .unwrap_or_else(|| self.options.size.table_cell_padding());
1356 let scale_factor = window.scale_factor();
1360 let device_pixels = |length: Pixels| (f32::from(length) * scale_factor).ceil();
1361 let mut content_pixels = device_pixels(content);
1362 if px(content_pixels / scale_factor) < content {
1365 content_pixels += 1.;
1366 }
1367 let width = content_pixels + device_pixels(padding.left) + device_pixels(padding.right);
1368 if self.resize_cols(col_ix, px(width / scale_factor), window, cx) {
1369 let new_widths = self.col_groups.iter().map(|g| g.width).collect();
1370 cx.emit(TableEvent::ColumnWidthsChanged(new_widths));
1371 }
1372 true
1373 }
1374
1375 fn resize_cols(
1380 &mut self,
1381 ix: usize,
1382 size: Pixels,
1383 _: &mut Window,
1384 cx: &mut Context<Self>,
1385 ) -> bool {
1386 if !self.col_resizable {
1387 return false;
1388 }
1389
1390 let mut changed = false;
1391 if let Some(col_group) = self.col_groups.get_mut(ix) {
1392 if col_group.is_resizable() {
1393 let new_width = size
1394 .max(col_group.column.min_width)
1395 .min(col_group.column.max_width);
1396 if col_group.width != new_width {
1397 col_group.width = new_width;
1398 changed = true;
1399 }
1400 }
1401 }
1402
1403 if changed {
1404 self.update_header_layout(cx);
1405 cx.notify();
1406 }
1407 changed
1408 }
1409
1410 fn perform_sort(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
1411 if !self.sortable {
1412 return;
1413 }
1414
1415 let sort = self.col_groups.get(col_ix).and_then(|g| g.column.sort);
1416 if sort.is_none() {
1417 return;
1418 }
1419
1420 let sort = sort.unwrap();
1421 let sort = match sort {
1422 ColumnSort::Ascending => ColumnSort::Default,
1423 ColumnSort::Descending => ColumnSort::Ascending,
1424 ColumnSort::Default => ColumnSort::Descending,
1425 };
1426
1427 for (ix, col_group) in self.col_groups.iter_mut().enumerate() {
1428 if ix == col_ix {
1429 col_group.column.sort = Some(sort);
1430 } else {
1431 if col_group.column.sort.is_some() {
1432 col_group.column.sort = Some(ColumnSort::Default);
1433 }
1434 }
1435 }
1436
1437 self.delegate_mut().perform_sort(col_ix, sort, window, cx);
1438
1439 cx.notify();
1440 }
1441
1442 fn move_column(
1443 &mut self,
1444 col_ix: usize,
1445 to_ix: usize,
1446 window: &mut Window,
1447 cx: &mut Context<Self>,
1448 ) {
1449 if col_ix == to_ix {
1450 return;
1451 }
1452
1453 self.delegate.move_column(col_ix, to_ix, window, cx);
1454 let col_group = self.col_groups.remove(col_ix);
1455 self.col_groups.insert(to_ix, col_group);
1456
1457 cx.emit(TableEvent::MoveColumn(col_ix, to_ix));
1458 cx.notify();
1459 }
1460
1461 fn drag_gap_at(&self, x: Pixels, drag_col_ix: usize) -> Option<usize> {
1465 let scrollable_cols = self.scrollable_cols();
1466
1467 let pointer_side = if scrollable_cols.start > 0 && x < self.fixed_head_cols_bounds.right() {
1472 Some(ColumnFixed::Left)
1473 } else if scrollable_cols.end < self.col_groups.len()
1474 && x >= self.fixed_right_head_cols_bounds.left()
1475 {
1476 Some(ColumnFixed::Right)
1477 } else {
1478 None
1479 };
1480 if self.col_fixed_side(drag_col_ix) != pointer_side {
1481 return None;
1482 }
1483
1484 let candidates = match pointer_side {
1488 Some(ColumnFixed::Left) => 0..scrollable_cols.start,
1489 Some(ColumnFixed::Right) => scrollable_cols.end..self.col_groups.len(),
1490 None => self.calculate_visible_leaf_col_range(scrollable_cols).0,
1491 };
1492
1493 let mut gap = candidates.start;
1495 for ix in candidates {
1496 if x < self.col_groups[ix].bounds.center().x {
1497 break;
1498 }
1499 gap = ix + 1;
1500 }
1501
1502 if gap == drag_col_ix || gap == drag_col_ix + 1 {
1505 None
1506 } else {
1507 Some(gap)
1508 }
1509 }
1510
1511 fn load_more_if_need(
1513 &mut self,
1514 rows_count: usize,
1515 visible_end: usize,
1516 window: &mut Window,
1517 cx: &mut Context<Self>,
1518 ) {
1519 let threshold = self.delegate.load_more_threshold();
1520 if visible_end >= rows_count.saturating_sub(threshold) {
1522 if !self.delegate.has_more(cx) {
1523 return;
1524 }
1525
1526 self._load_more_task = cx.spawn_in(window, async move |view, window| {
1527 _ = view.update_in(window, |view, window, cx| {
1528 view.delegate.load_more(window, cx);
1529 });
1530 });
1531 }
1532 }
1533
1534 fn update_visible_range_if_need(
1535 &mut self,
1536 visible_range: Range<usize>,
1537 items_count: usize,
1538 axis: Axis,
1539 window: &mut Window,
1540 cx: &mut Context<Self>,
1541 ) {
1542 if visible_range.len() <= 1 && items_count > 1 {
1545 return;
1546 }
1547
1548 let end = visible_range.end.min(items_count);
1550 let visible_range = visible_range.start.min(end)..end;
1551 if visible_range.is_empty() && items_count > 0 {
1553 return;
1554 }
1555
1556 if axis == Axis::Vertical {
1557 if self.visible_range.rows == visible_range {
1558 return;
1559 }
1560 self.delegate_mut()
1561 .visible_rows_changed(visible_range.clone(), window, cx);
1562 self.visible_range.rows = visible_range;
1563 } else {
1564 if self.visible_range.cols == visible_range {
1565 return;
1566 }
1567 self.delegate_mut()
1568 .visible_columns_changed(visible_range.clone(), window, cx);
1569 self.visible_range.cols = visible_range;
1570 }
1571 }
1572
1573 fn render_cell(
1574 &self,
1575 _row_ix: Option<usize>,
1576 col_ix: usize,
1577 _window: &mut Window,
1578 cx: &mut Context<Self>,
1579 ) -> Div {
1580 let Some(col_group) = self.col_groups.get(col_ix) else {
1581 return div();
1582 };
1583 let is_rtl = gpui_base::LayoutDirection::global(cx).is_rtl();
1584
1585 let col_width = col_group.width;
1586 let col_padding = col_group.column.paddings;
1587
1588 div()
1589 .w(col_width)
1590 .h_full()
1591 .flex_shrink_0()
1592 .overflow_hidden()
1593 .whitespace_nowrap()
1594 .table_cell_size(self.options.size)
1595 .map(|this| match (col_group.column.align, is_rtl) {
1599 (TextAlign::Center, _) => this.text_center(),
1600 (TextAlign::Right, false) | (TextAlign::Left, true) => this.text_right(),
1601 (TextAlign::Right, true) => this.text_left(),
1602 _ => this,
1603 })
1604 .map(|this| match col_padding {
1605 Some(padding) => this
1606 .pl(padding.left)
1607 .pr(padding.right)
1608 .pt(padding.top)
1609 .pb(padding.bottom),
1610 None => this,
1611 })
1612 }
1613
1614 fn a11y_cell<E>(&self, cell: E, row_ix: usize, col_ix: usize, window: &Window, cx: &App) -> E
1620 where
1621 E: gpui::StatefulInteractiveElement + FluentBuilder,
1622 {
1623 let cell = if self.cell_selectable {
1624 let is_selected = self.selected_cell() == Some((row_ix, col_ix));
1625 cell.role(gpui::Role::GridCell)
1626 .aria_selected(is_selected)
1627 .when(
1630 is_selected && self.focus_handle.is_focused(window),
1631 |this| this.aria_active_descendant(),
1632 )
1633 } else {
1634 cell.role(gpui::Role::Cell)
1635 };
1636 let label = if window.is_a11y_active() || cfg!(feature = "test-support") {
1640 self.delegate.cell_label(row_ix, col_ix, cx)
1641 } else {
1642 None
1643 };
1644 cell.aria_column_index(col_ix)
1645 .when_some(label, |this, label| this.aria_label(label))
1646 }
1647
1648 fn render_col_wrap(
1651 &self,
1652 _row_ix: Option<usize>,
1653 col_ix: usize,
1654 _: &mut Window,
1655 cx: &mut Context<Self>,
1656 ) -> Div {
1657 let el = h_flex().h_full();
1658 let selectable = self.col_selectable
1659 && self
1660 .col_groups
1661 .get(col_ix)
1662 .map(|col_group| col_group.column.selectable)
1663 .unwrap_or(false);
1664
1665 if selectable && self.selected_col() == Some(col_ix) {
1668 el.bg(cx.theme().tokens.table_active)
1669 } else {
1670 el
1671 }
1672 }
1673
1674 fn render_leading_resize_handle(
1681 &self,
1682 ix: usize,
1683 _: &mut Window,
1684 cx: &mut Context<Self>,
1685 ) -> impl IntoElement {
1686 let is_fixed_right = |ix: usize| {
1690 self.col_fixed
1691 && self.col_groups.get(ix).and_then(|col| col.column.fixed)
1692 == Some(ColumnFixed::Right)
1693 };
1694 let Some(prev) = ix.checked_sub(1).filter(|prev| {
1695 self.is_col_resizable(*prev) && (!is_fixed_right(ix) || is_fixed_right(*prev))
1696 }) else {
1697 return div().into_any_element();
1698 };
1699
1700 self.resize_handle_band(prev, ("resizable-handle-leading", ix).into(), cx)
1701 .absolute()
1702 .top_0()
1703 .left_0()
1704 .h_full()
1705 .w(HANDLE_PADDING)
1706 .into_any_element()
1707 }
1708
1709 fn render_resize_handle(
1717 &self,
1718 ix: usize,
1719 _: &mut Window,
1720 cx: &mut Context<Self>,
1721 ) -> impl IntoElement {
1722 if !self.is_col_resizable(ix) {
1723 return div().into_any_element();
1724 }
1725
1726 let group_id = SharedString::from(format!("resizable-handle:{}", ix));
1727
1728 self.resize_handle_band(ix, ("resizable-handle", ix).into(), cx)
1729 .group(group_id.clone())
1730 .h_full()
1731 .w(HANDLE_PADDING)
1732 .ml(-HANDLE_PADDING)
1733 .justify_end()
1734 .items_center()
1735 .child(
1736 div()
1737 .h_full()
1738 .justify_center()
1739 .bg(cx.theme().table_row_border)
1740 .group_hover(&group_id, |this| this.bg(cx.theme().border).h_full())
1741 .w(px(1.)),
1742 )
1743 .into_any_element()
1744 }
1745
1746 fn is_col_resizable(&self, ix: usize) -> bool {
1747 self.col_resizable
1748 && self
1749 .col_groups
1750 .get(ix)
1751 .map(|col| col.is_resizable())
1752 .unwrap_or(false)
1753 }
1754
1755 fn resize_handle_band(
1765 &self,
1766 ix: usize,
1767 id: ElementId,
1768 cx: &mut Context<Self>,
1769 ) -> Stateful<Div> {
1770 h_flex()
1771 .id(id)
1772 .occlude()
1773 .cursor_col_resize()
1774 .on_drag_move(
1775 cx.listener(move |view, e: &DragMoveEvent<ResizeColumn>, window, cx| {
1776 match e.drag(cx) {
1777 ResizeColumn((entity_id, ix)) => {
1778 if cx.entity_id() != *entity_id {
1779 return;
1780 }
1781
1782 let ix = *ix;
1789 if view.fitted_col == Some(ix) {
1790 return;
1791 }
1792 view.resizing_col = Some(ix);
1793
1794 let col_group = view
1795 .col_groups
1796 .get(ix)
1797 .expect("BUG: invalid col index")
1798 .clone();
1799
1800 let Some(origin) = view.resize_origin else {
1806 return;
1807 };
1808 view.resize_cols(
1809 ix,
1810 origin.width + (e.event.position.x - origin.x),
1811 window,
1812 cx,
1813 );
1814
1815 view.scroll_table_by_col_resizing(e.event.position, &col_group);
1817 }
1818 };
1819 }),
1820 )
1821 .on_drag(ResizeColumn((cx.entity_id(), ix)), |drag, _, _, cx| {
1822 cx.stop_propagation();
1823 cx.new(|_| drag.clone())
1824 })
1825 .on_mouse_down(
1826 MouseButton::Left,
1827 cx.listener(move |view, e: &MouseDownEvent, window, cx| {
1828 view.resize_origin = view.col_groups.get(ix).map(|col_group| ResizeOrigin {
1829 x: e.position.x,
1830 width: col_group.width,
1831 });
1832 if e.click_count == 1 {
1833 view.fitted_col = None;
1834 } else if e.click_count == 2 && view.fit_col(ix, window, cx) {
1835 view.fitted_col = Some(ix);
1836 }
1837 }),
1838 )
1839 .on_mouse_up_out(
1840 MouseButton::Left,
1841 cx.listener(|view, _, _, cx| {
1842 view.resize_origin = None;
1843 if view.resizing_col.is_none() {
1844 return;
1845 }
1846
1847 view.resizing_col = None;
1848
1849 let new_widths = view.col_groups.iter().map(|g| g.width).collect();
1850 cx.emit(TableEvent::ColumnWidthsChanged(new_widths));
1851 cx.notify();
1852 }),
1853 )
1854 }
1855
1856 fn render_fixed_cols_border(&self, side: ColumnFixed, cx: &App) -> Option<Div> {
1859 self.options.fixed_cols_border.then(|| {
1860 div()
1861 .absolute()
1862 .top_0()
1863 .bottom_0()
1864 .w_0()
1865 .flex_shrink_0()
1866 .border_color(cx.theme().border)
1867 .map(|this| match side {
1868 ColumnFixed::Left => this.right_0().border_r_1(),
1869 ColumnFixed::Right => this.left_0().border_l_1(),
1870 })
1871 })
1872 }
1873
1874 fn render_row_header_cell(
1876 &self,
1877 row_ix: usize,
1878 is_head: bool,
1879 cx: &mut Context<Self>,
1880 ) -> impl IntoElement {
1881 div()
1882 .id(("row-header", row_ix))
1883 .w_3()
1884 .h_full()
1885 .border_r_1()
1886 .border_color(cx.theme().table_row_border)
1887 .bg(cx.theme().tokens.table_head)
1888 .flex_shrink_0()
1889 .table_cell_size(self.options.size)
1890 .when(!is_head, |this| {
1891 this.when(self.row_selectable, |this| {
1892 this.on_click(cx.listener(move |table, e: &ClickEvent, _window, cx| {
1893 cx.stop_propagation();
1894 if table.selects_row_on_click(e, cx) {
1895 table.select_row(row_ix, true, cx);
1896 }
1897 }))
1898 })
1899 })
1900 }
1901
1902 fn render_sort_icon(
1903 &self,
1904 col_ix: usize,
1905 col_group: &ColGroup,
1906 _: &mut Window,
1907 cx: &mut Context<Self>,
1908 ) -> Option<impl IntoElement> {
1909 if !self.sortable {
1910 return None;
1911 }
1912
1913 let Some(sort) = col_group.column.sort else {
1914 return None;
1915 };
1916
1917 let (icon, is_on) = match sort {
1918 ColumnSort::Ascending => (IconName::SortAscending, true),
1919 ColumnSort::Descending => (IconName::SortDescending, true),
1920 ColumnSort::Default => (IconName::ChevronsUpDown, false),
1921 };
1922
1923 Some(
1924 div()
1925 .id(("icon-sort", col_ix))
1926 .test_support()
1927 .role(gpui::Role::Button)
1928 .aria_label(t!("Table.SortBy", column = col_group.column.name).to_string())
1929 .p(px(2.))
1930 .rounded(cx.theme().radius / 2.)
1931 .map(|this| match is_on {
1932 true => this,
1933 false => this.opacity(0.5),
1934 })
1935 .hover(|this| this.bg(cx.theme().tokens.secondary).opacity(7.))
1936 .active(|this| this.bg(cx.theme().tokens.secondary_active).opacity(1.))
1937 .on_click(
1938 cx.listener(move |table, _, window, cx| table.perform_sort(col_ix, window, cx)),
1939 )
1940 .child(
1941 Icon::new(icon)
1942 .size_3()
1943 .text_color(cx.theme().secondary_foreground),
1944 ),
1945 )
1946 }
1947
1948 fn render_th(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) -> Div {
1953 let entity_id = cx.entity_id();
1954 let col_group = self.col_groups.get(col_ix).expect("BUG: invalid col index");
1955
1956 let movable = self.col_movable && col_group.column.movable;
1957 let paddings = col_group.column.paddings;
1958 let name = col_group.column.name.clone();
1959
1960 h_flex()
1961 .h_full()
1962 .child(
1963 self.render_cell(None, col_ix, window, cx)
1964 .when(
1969 self.options.header_row_height.is_some() && paddings.is_none(),
1970 |this| this.py_0(),
1971 )
1972 .id(("col-header", col_ix))
1973 .role(gpui::Role::ColumnHeader)
1974 .aria_label(name.clone())
1975 .aria_column_index(col_ix)
1976 .test_support()
1977 .on_click(cx.listener(move |this, _, window, cx| {
1978 this.on_col_head_click(col_ix, window, cx);
1979 }))
1980 .child(
1981 h_flex()
1982 .size_full()
1983 .justify_between()
1984 .items_center()
1985 .child(self.delegate.render_th(col_ix, window, cx))
1986 .when_some(paddings, |this, paddings| {
1987 let offset_pr =
1989 self.options.size.table_cell_padding().right - paddings.right;
1990 this.pr(offset_pr.max(px(0.)))
1991 })
1992 .children(self.render_sort_icon(col_ix, &col_group, window, cx)),
1993 )
1994 .when(movable, |this| {
1995 this.on_drag(
1996 DragColumn {
1997 entity_id,
1998 col_ix,
1999 name,
2000 width: col_group.width,
2001 },
2002 |drag, _, _, cx| {
2003 cx.stop_propagation();
2004 cx.new(|_| drag.clone())
2005 },
2006 )
2007 })
2008 .map(|this| {
2009 let last_gap = col_ix + 1 == self.col_groups.len();
2014 match self.col_drag_gap {
2015 Some(gap)
2016 if cx.has_active_drag()
2017 && (gap == col_ix || (last_gap && gap == col_ix + 1)) =>
2018 {
2019 let right_side = gap == col_ix + 1;
2020 this.relative().child(
2021 div()
2022 .absolute()
2023 .top_0()
2024 .bottom_0()
2025 .w(px(2.))
2026 .map(|d| if right_side { d.right_0() } else { d.left_0() })
2027 .bg(cx.theme().drag_border),
2028 )
2029 }
2030 _ => this,
2031 }
2032 }),
2033 )
2034 .child(self.render_resize_handle(col_ix, window, cx))
2036 .child(self.render_leading_resize_handle(col_ix, window, cx))
2038 .on_prepaint({
2040 let view = cx.entity();
2041 move |bounds, _, cx| view.update(cx, |r, _| r.col_groups[col_ix].bounds = bounds)
2042 })
2043 }
2044
2045 fn calculate_visible_leaf_col_range(
2055 &self,
2056 scrollable_cols: Range<usize>,
2057 ) -> (Range<usize>, Pixels) {
2058 let (left_columns_count, total_cols) = (scrollable_cols.start, scrollable_cols.end);
2059
2060 if self.bounds.size.width == px(0.) {
2061 return (scrollable_cols, px(0.));
2062 }
2063
2064 let fixed_width =
2065 self.fixed_head_cols_bounds.size.width + self.fixed_right_head_cols_bounds.size.width;
2066 let available_width = (self.bounds.size.width - fixed_width).max(px(0.));
2067 let scroll_x = (-self.horizontal_scroll_handle.offset().x).max(px(0.));
2070
2071 let mut range_start = left_columns_count;
2075 let mut left_spacer = px(0.);
2076 let mut cumulative = px(0.);
2077 for i in left_columns_count..total_cols {
2078 let right_edge = cumulative + self.col_groups[i].width;
2079 if right_edge > scroll_x {
2080 range_start = i;
2081 left_spacer = cumulative;
2082 break;
2083 }
2084 cumulative = right_edge;
2085 }
2086
2087 let right_bound = scroll_x + available_width + px(200.);
2091 let mut range_end = total_cols;
2092 let mut cumulative = left_spacer; for i in range_start..total_cols {
2094 cumulative += self.col_groups[i].width;
2095 if cumulative > right_bound {
2096 range_end = (i + 1).min(total_cols);
2097 break;
2098 }
2099 }
2100
2101 (range_start..range_end, left_spacer)
2102 }
2103
2104 fn render_table_header(
2105 &mut self,
2106 scrollable_cols: Range<usize>,
2107 window: &mut Window,
2108 cx: &mut Context<Self>,
2109 ) -> impl IntoElement {
2110 let horizontal_scroll_handle = self.horizontal_scroll_handle.clone();
2111
2112 let total_cols = self.col_groups.len();
2126 let left_columns_count = scrollable_cols.start;
2127 let right_columns_start = scrollable_cols.end;
2128 let (visible_col_range, left_spacer) =
2129 self.calculate_visible_leaf_col_range(scrollable_cols.clone());
2130
2131 let layout_len = self.header_layout.len();
2132 let header_row_height = self.header_row_height();
2133
2134 if left_columns_count == 0 {
2136 self.fixed_head_cols_bounds = Bounds::default();
2137 }
2138 if right_columns_start == total_cols {
2139 self.fixed_right_head_cols_bounds = Bounds::default();
2140 }
2141
2142 let mut header = self.delegate_mut().render_header(window, cx);
2143 let style = header.style().clone();
2144 let layout = self.header_layout.clone();
2145
2146 header
2147 .role(gpui::Role::Row)
2150 .aria_row_index(0)
2151 .h_flex()
2152 .w_full()
2153 .flex_shrink_0()
2154 .bg(cx.theme().tokens.table_head)
2155 .text_color(cx.theme().table_head_foreground)
2156 .refine_style(&style)
2157 .on_drag_move(cx.listener(|table, e: &DragMoveEvent<DragColumn>, _, cx| {
2158 let drag = e.drag(cx);
2159 let (drag_entity_id, drag_col_ix) = (drag.entity_id, drag.col_ix);
2160
2161 let gap =
2162 if drag_entity_id == cx.entity_id() && e.bounds.contains(&e.event.position) {
2163 table.drag_gap_at(e.event.position.x, drag_col_ix)
2164 } else {
2165 None
2166 };
2167
2168 if table.col_drag_gap != gap {
2169 table.col_drag_gap = gap;
2170 cx.notify();
2171 }
2172 }))
2173 .on_drop(cx.listener(|table, drag: &DragColumn, window, cx| {
2174 if drag.entity_id != cx.entity_id() {
2175 return;
2176 }
2177
2178 let Some(gap) = table.col_drag_gap.take() else {
2180 return;
2181 };
2182 let to_ix = if drag.col_ix < gap { gap - 1 } else { gap };
2183 table.move_column(drag.col_ix, to_ix, window, cx);
2184 }))
2185 .when(self.cell_selectable && self.row_header, |this| {
2186 this.child(self.render_row_header_cell(0, true, cx))
2187 })
2188 .when(left_columns_count > 0, |this| {
2189 this.child(self.render_fixed_head_cols(
2190 0..left_columns_count,
2191 ColumnFixed::Left,
2192 window,
2193 cx,
2194 ))
2195 })
2196 .child(
2197 h_flex()
2199 .id("table-head")
2200 .size_full()
2201 .overflow_scroll()
2202 .relative()
2203 .track_scroll(&horizontal_scroll_handle)
2204 .bg(cx.theme().tokens.table_head)
2205 .child(v_flex().min_w_full().flex_shrink_0().children(
2206 layout.iter().enumerate().map(|(row_ix, row_cells)| {
2207 let is_leaf_row = row_ix + 1 == layout_len;
2208 h_flex()
2209 .min_w_full()
2210 .h(header_row_height)
2211 .border_b_1()
2212 .border_color(cx.theme().border)
2213 .map(|this| {
2214 if is_leaf_row {
2215 this.when(left_spacer > px(0.), |r| {
2220 r.child(div().w(left_spacer).h_full().flex_shrink_0())
2221 })
2222 .children(row_cells.iter().filter_map(|cell| {
2223 if cell.is_leaf {
2224 let ix = cell.leaf_col_ix?;
2225 if !visible_col_range.contains(&ix) {
2226 return None;
2227 }
2228 Some(
2229 self.render_th(ix, window, cx)
2230 .into_any_element(),
2231 )
2232 } else {
2233 None
2234 }
2235 }))
2236 .when(visible_col_range.end < right_columns_start, |r| {
2237 let right_spacer: Pixels = self.col_groups
2238 [visible_col_range.end..right_columns_start]
2239 .iter()
2240 .map(|g| g.width)
2241 .sum();
2242 r.child(div().w(right_spacer).h_full().flex_shrink_0())
2243 })
2244 .child(self.delegate.render_last_empty_col(window, cx))
2245 } else {
2246 this.children(row_cells.iter().filter_map(|cell| {
2249 if scrollable_cols.contains(&cell.start_leaf_col_ix) {
2250 if cell.is_leaf {
2251 if let Some(ix) = cell.leaf_col_ix {
2252 return Some(
2253 self.render_th(ix, window, cx)
2254 .into_any_element(),
2255 );
2256 }
2257 } else {
2258 return Some(
2259 self.delegate_mut()
2260 .render_group_th(
2261 &cell.label,
2262 cell.col_span,
2263 cell.width,
2264 window,
2265 cx,
2266 )
2267 .into_any_element(),
2268 );
2269 }
2270 }
2271 None
2272 }))
2273 .child(self.delegate.render_last_empty_col(window, cx))
2274 }
2275 })
2276 }),
2277 )),
2278 )
2279 .when(right_columns_start < total_cols, |this| {
2280 this.child(self.render_fixed_head_cols(
2281 right_columns_start..total_cols,
2282 ColumnFixed::Right,
2283 window,
2284 cx,
2285 ))
2286 })
2287 }
2288
2289 fn render_fixed_head_cols(
2292 &mut self,
2293 cols: Range<usize>,
2294 side: ColumnFixed,
2295 window: &mut Window,
2296 cx: &mut Context<Self>,
2297 ) -> impl IntoElement {
2298 let view = cx.entity();
2299 let header_row_height = self.header_row_height();
2300 let layout = self.header_layout.clone();
2301
2302 h_flex()
2303 .relative()
2304 .h_full()
2305 .flex_shrink_0()
2306 .bg(cx.theme().tokens.table_head)
2307 .child(
2308 v_flex()
2309 .min_w_full()
2310 .flex_shrink_0()
2311 .children(layout.iter().map(|row_cells| {
2312 h_flex()
2313 .min_w_full()
2314 .h(header_row_height)
2315 .border_b_1()
2316 .border_color(cx.theme().border)
2317 .children(row_cells.iter().filter_map(|cell| {
2318 if !cols.contains(&cell.start_leaf_col_ix) {
2319 return None;
2320 }
2321
2322 if cell.is_leaf {
2323 let ix = cell.leaf_col_ix?;
2324 Some(self.render_th(ix, window, cx).into_any_element())
2325 } else {
2326 Some(
2327 self.delegate_mut()
2328 .render_group_th(
2329 &cell.label,
2330 cell.col_span,
2331 cell.width,
2332 window,
2333 cx,
2334 )
2335 .into_any_element(),
2336 )
2337 }
2338 }))
2339 })),
2340 )
2341 .children(self.render_fixed_cols_border(side, cx))
2342 .on_prepaint(move |bounds, _, cx| {
2343 view.update(cx, |table, _| match side {
2344 ColumnFixed::Left => table.fixed_head_cols_bounds = bounds,
2345 ColumnFixed::Right => table.fixed_right_head_cols_bounds = bounds,
2346 })
2347 })
2348 }
2349
2350 #[allow(clippy::too_many_arguments)]
2351 fn render_table_row(
2352 &mut self,
2353 row_ix: usize,
2354 rows_count: usize,
2355 scrollable_cols: Range<usize>,
2356 col_sizes: Rc<Vec<gpui::Size<Pixels>>>,
2357 columns_count: usize,
2358 is_filled: bool,
2359 window: &mut Window,
2360 cx: &mut Context<Self>,
2361 ) -> gpui::AnyElement {
2362 let is_stripe_row = self.options.stripe && row_ix % 2 != 0;
2363 let is_selected = self.selected_row() == Some(row_ix);
2366 let view = cx.entity();
2367 let row_height = self.options.size.table_row_height();
2368
2369 if row_ix < rows_count {
2370 let is_last_row = row_ix + 1 == rows_count;
2371 let need_render_border = is_selected || !is_last_row || !is_filled;
2372
2373 let mut tr = self.delegate.render_tr(row_ix, window, cx);
2374 let style = tr.style().clone();
2375 let label = if window.is_a11y_active() || cfg!(feature = "test-support") {
2377 self.delegate.row_label(row_ix, cx)
2378 } else {
2379 None
2380 };
2381
2382 tr.test_support()
2383 .role(gpui::Role::Row)
2384 .aria_row_index(row_ix + 1)
2386 .when_some(label, |this, label| this.aria_label(label))
2387 .aria_selected(is_selected)
2388 .when(
2391 is_selected && self.focus_handle.is_focused(window),
2392 |this| this.aria_active_descendant(),
2393 )
2394 .h_flex()
2395 .w_full()
2396 .h(row_height)
2397 .when(need_render_border, |this| {
2398 this.border_b_1().border_color(cx.theme().table_row_border)
2399 })
2400 .when(is_stripe_row, |this| this.bg(cx.theme().tokens.table_even))
2401 .refine_style(&style)
2402 .hover(|this| {
2403 if is_selected || self.right_clicked_row == Some(row_ix) {
2404 this
2405 } else {
2406 this.bg(cx.theme().tokens.table_hover)
2407 }
2408 })
2409 .when(self.cell_selectable && self.row_header, |this| {
2410 this.child(self.render_row_header_cell(row_ix, false, cx))
2411 })
2412 .when(scrollable_cols.start > 0, |this| {
2413 this.child(self.render_fixed_cells(
2414 row_ix,
2415 0..scrollable_cols.start,
2416 ColumnFixed::Left,
2417 window,
2418 cx,
2419 ))
2420 })
2421 .child(
2422 h_flex()
2423 .flex_1()
2424 .h_full()
2425 .overflow_hidden()
2426 .relative()
2427 .child(
2428 crate::virtual_list::virtual_list(
2429 view,
2430 row_ix,
2431 Axis::Horizontal,
2432 col_sizes,
2433 {
2434 let scrollable_cols = scrollable_cols.clone();
2435 move |table, visible_range: Range<usize>, window, cx| {
2436 table.update_visible_range_if_need(
2437 visible_range.clone(),
2438 scrollable_cols.len(),
2439 Axis::Horizontal,
2440 window,
2441 cx,
2442 );
2443
2444 let mut items = Vec::with_capacity(
2445 visible_range.end - visible_range.start,
2446 );
2447
2448 visible_range.for_each(|col_ix| {
2449 let col_ix = col_ix + scrollable_cols.start;
2450 let is_cell_selected =
2451 table.selected_cell() == Some((row_ix, col_ix));
2452 let is_cell_right_clicked =
2453 table.right_clicked_cell == Some((row_ix, col_ix));
2454
2455 let el = table
2456 .render_col_wrap(Some(row_ix), col_ix, window, cx)
2457 .child(
2458 table
2459 .a11y_cell(
2460 table
2461 .render_cell(
2462 Some(row_ix),
2463 col_ix,
2464 window,
2465 cx,
2466 )
2467 .id(format!(
2468 "table-cell-{}:{}",
2469 row_ix, col_ix
2470 ))
2471 .test_support(),
2472 row_ix,
2473 col_ix,
2474 window,
2475 cx,
2476 )
2477 .relative()
2478 .child(table.measure_render_td(
2479 row_ix, col_ix, window, cx,
2480 ))
2481 .when(is_cell_selected, |this| {
2482 this.child(
2483 div()
2484 .absolute()
2485 .inset_0()
2486 .bg(cx
2487 .theme()
2488 .tokens
2489 .table_active)
2490 .border_1()
2491 .border_color(
2492 cx.theme()
2493 .table_active_border,
2494 ),
2495 )
2496 })
2497 .when(
2498 is_cell_right_clicked
2499 && !is_cell_selected,
2500 |this| {
2501 this.child(
2502 div()
2503 .absolute()
2504 .inset_0()
2505 .border_1()
2506 .border_color(
2507 cx.theme()
2508 .table_active_border
2509 .opacity(0.5),
2510 ),
2511 )
2512 },
2513 )
2514 .when(table.cell_selectable, |this| {
2515 this.on_click(cx.listener(
2516 move |table, e, window, cx| {
2517 cx.stop_propagation();
2518 table.on_cell_click(
2519 e, row_ix, col_ix, window,
2520 cx,
2521 );
2522 },
2523 ))
2524 .on_mouse_down(
2525 MouseButton::Right,
2526 cx.listener(
2527 move |table, e, window, cx| {
2528 table.on_cell_right_click(
2529 e, row_ix, col_ix,
2530 window, cx,
2531 );
2532 },
2533 ),
2534 )
2535 }),
2536 );
2537
2538 items.push(el);
2539 });
2540
2541 items
2542 }
2543 },
2544 )
2545 .with_scroll_handle(&self.horizontal_scroll_handle),
2546 )
2547 .child(self.delegate.render_last_empty_col(window, cx)),
2548 )
2549 .when(scrollable_cols.end < self.col_groups.len(), |this| {
2550 this.child(self.render_fixed_cells(
2551 row_ix,
2552 scrollable_cols.end..self.col_groups.len(),
2553 ColumnFixed::Right,
2554 window,
2555 cx,
2556 ))
2557 })
2558 .when(is_selected, |this| {
2560 let bg = if cx.theme().list.active_highlight {
2561 cx.theme().tokens.table_active
2562 } else {
2563 cx.theme().tokens.accent
2564 };
2565 this.bg(bg)
2566 })
2567 .when(self.right_clicked_row == Some(row_ix), |this| {
2569 this.border_color(gpui::transparent_white()).child(
2570 div()
2571 .top(if row_ix == 0 { px(0.) } else { px(-1.) })
2572 .left(px(0.))
2573 .right(px(0.))
2574 .bottom(px(-1.))
2575 .absolute()
2576 .border_1()
2577 .border_color(cx.theme().selection),
2578 )
2579 })
2580 .on_mouse_down(
2581 MouseButton::Right,
2582 cx.listener(move |this, e, window, cx| {
2583 this.on_row_right_click(e, Some(row_ix), window, cx);
2584 }),
2585 )
2586 .on_click(cx.listener(move |this, e, window, cx| {
2587 this.on_row_left_click(e, row_ix, window, cx);
2588 }))
2589 .into_any_element()
2590 } else {
2591 let cols_width: Pixels = self
2592 .col_groups
2593 .iter()
2594 .take(columns_count)
2595 .map(|col_group| col_group.width)
2596 .sum();
2597
2598 self.delegate
2600 .render_tr(row_ix, window, cx)
2601 .h_flex()
2602 .w_full()
2603 .h(row_height)
2604 .border_b_1()
2605 .border_color(cx.theme().table_row_border)
2606 .when(is_stripe_row, |this| this.bg(cx.theme().tokens.table_even))
2607 .when(self.cell_selectable && self.row_header, |this| {
2608 this.child(
2610 div()
2611 .w(px(40.))
2612 .h_full()
2613 .flex_shrink_0()
2614 .table_cell_size(self.options.size),
2615 )
2616 })
2617 .child(div().flex_shrink_0().h_full().w(cols_width))
2621 .child(self.delegate.render_last_empty_col(window, cx))
2622 .into_any_element()
2623 }
2624 }
2625
2626 fn render_fixed_cells(
2628 &mut self,
2629 row_ix: usize,
2630 cols: Range<usize>,
2631 side: ColumnFixed,
2632 window: &mut Window,
2633 cx: &mut Context<Self>,
2634 ) -> impl IntoElement {
2635 let items: Vec<_> = cols
2636 .map(|col_ix| {
2637 let is_cell_selected = self.selected_cell() == Some((row_ix, col_ix));
2638 let is_cell_right_clicked = self.right_clicked_cell == Some((row_ix, col_ix));
2639
2640 self.render_col_wrap(Some(row_ix), col_ix, window, cx)
2641 .child(
2642 self.a11y_cell(
2643 self.render_cell(Some(row_ix), col_ix, window, cx)
2644 .id(format!("table-cell:{}:{}", row_ix, col_ix))
2645 .test_support(),
2646 row_ix,
2647 col_ix,
2648 window,
2649 cx,
2650 )
2651 .relative()
2652 .child(self.measure_render_td(row_ix, col_ix, window, cx))
2653 .when(is_cell_selected, |this| {
2654 this.child(
2655 div()
2656 .absolute()
2657 .inset_0()
2658 .bg(cx.theme().tokens.table_active)
2659 .border_1()
2660 .border_color(cx.theme().table_active_border),
2661 )
2662 })
2663 .when(is_cell_right_clicked && !is_cell_selected, |this| {
2664 this.child(
2665 div()
2666 .absolute()
2667 .inset_0()
2668 .border_1()
2669 .border_color(cx.theme().table_active_border.opacity(0.5)),
2670 )
2671 })
2672 .when(self.cell_selectable, |this| {
2673 this.on_click(cx.listener(move |table, e, window, cx| {
2674 table.on_cell_click(e, row_ix, col_ix, window, cx);
2675 }))
2676 .on_mouse_down(
2677 MouseButton::Right,
2678 cx.listener(move |table, e, window, cx| {
2679 table.on_cell_right_click(e, row_ix, col_ix, window, cx);
2680 }),
2681 )
2682 }),
2683 )
2684 })
2685 .collect();
2686
2687 h_flex()
2688 .relative()
2689 .h_full()
2690 .flex_shrink_0()
2691 .children(items)
2692 .children(self.render_fixed_cols_border(side, cx))
2693 }
2694
2695 fn calculate_extra_rows_needed(
2697 &self,
2698 total_height: Pixels,
2699 actual_height: Pixels,
2700 row_height: Pixels,
2701 ) -> usize {
2702 let mut extra_rows_needed = 0;
2703
2704 let remaining_height = total_height - actual_height;
2705 if remaining_height > px(0.) {
2706 extra_rows_needed = (remaining_height / row_height).floor() as usize;
2707 }
2708
2709 extra_rows_needed
2710 }
2711
2712 #[inline]
2713 fn measure_render_td(
2714 &mut self,
2715 row_ix: usize,
2716 col_ix: usize,
2717 window: &mut Window,
2718 cx: &mut Context<Self>,
2719 ) -> impl IntoElement {
2720 if !crate::measure_enable() {
2721 return self
2722 .delegate
2723 .render_td(row_ix, col_ix, window, cx)
2724 .into_any_element();
2725 }
2726
2727 let start = std::time::Instant::now();
2728 let el = self.delegate.render_td(row_ix, col_ix, window, cx);
2729 self._measure.push(start.elapsed());
2730 el.into_any_element()
2731 }
2732
2733 fn measure(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
2734 if !crate::measure_enable() {
2735 return;
2736 }
2737
2738 if self._measure.len() > 0 {
2740 let total = self
2741 ._measure
2742 .iter()
2743 .fold(Duration::default(), |acc, d| acc + *d);
2744 let avg = total / self._measure.len() as u32;
2745 eprintln!(
2746 "last render {} cells total: {:?}, avg: {:?}",
2747 self._measure.len(),
2748 total,
2749 avg,
2750 );
2751 }
2752 self._measure.clear();
2753 }
2754
2755 fn render_vertical_scrollbar(
2756 &mut self,
2757 _: &mut Window,
2758 _: &mut Context<Self>,
2759 ) -> Option<impl IntoElement> {
2760 Some(
2761 div()
2762 .absolute()
2763 .top(self.header_band_height())
2764 .right_0()
2765 .bottom_0()
2766 .w(Scrollbar::width())
2767 .child(
2768 Scrollbar::vertical(&self.vertical_scroll_handle)
2769 .viewport_from_layout()
2770 .when_some(self.options.scrollbar_mode, |this, mode| this.mode(mode))
2771 .max_fps(60),
2772 ),
2773 )
2774 }
2775
2776 fn render_horizontal_scrollbar(
2777 &mut self,
2778 _: &mut Window,
2779 _: &mut Context<Self>,
2780 ) -> impl IntoElement {
2781 div()
2782 .absolute()
2783 .left(self.fixed_head_cols_bounds.size.width)
2784 .right(self.fixed_right_head_cols_bounds.size.width)
2785 .bottom_0()
2786 .h(Scrollbar::width())
2787 .child(
2788 Scrollbar::horizontal(&self.horizontal_scroll_handle)
2789 .viewport_from_layout()
2790 .when_some(self.options.scrollbar_mode, |this, mode| this.mode(mode)),
2791 )
2792 }
2793}
2794
2795impl<D> Focusable for TableState<D>
2796where
2797 D: TableDelegate,
2798{
2799 fn focus_handle(&self, _cx: &gpui::App) -> FocusHandle {
2800 self.focus_handle.clone()
2801 }
2802}
2803impl<D> EventEmitter<TableEvent> for TableState<D> where D: TableDelegate {}
2804
2805impl<D> Render for TableState<D>
2806where
2807 D: TableDelegate,
2808{
2809 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2810 self.measure(window, cx);
2811
2812 let columns_count = self.delegate.columns_count(cx);
2813 let scrollable_cols = self.scrollable_cols();
2814 let rows_count = self.delegate.rows_count(cx);
2815 let loading = self.delegate.loading(cx);
2816
2817 let row_height = self.options.size.table_row_height();
2818 let total_height = self
2819 .vertical_scroll_handle
2820 .0
2821 .borrow()
2822 .base_handle
2823 .bounds()
2824 .size
2825 .height;
2826 let actual_height = row_height * rows_count as f32;
2827 let extra_rows_count =
2828 self.calculate_extra_rows_needed(total_height, actual_height, row_height);
2829 let render_rows_count = if self.options.stripe {
2830 rows_count + extra_rows_count
2831 } else {
2832 rows_count
2833 };
2834 let has_right_click = self.right_clicked_row.is_some() || self.right_clicked_cell.is_some();
2835 let is_filled = total_height > Pixels::ZERO && total_height <= actual_height;
2836
2837 let loading_view = if loading {
2838 Some(
2839 self.delegate
2840 .render_loading(self.options.size, window, cx)
2841 .into_any_element(),
2842 )
2843 } else {
2844 None
2845 };
2846
2847 let empty_view = if rows_count == 0 {
2848 self.update_visible_range_if_need(0..0, 0, Axis::Vertical, window, cx);
2850 Some(
2851 div()
2852 .size_full()
2853 .child(self.delegate.render_empty(window, cx))
2854 .into_any_element(),
2855 )
2856 } else {
2857 None
2858 };
2859
2860 let inner_table = v_flex()
2861 .id("table-inner")
2862 .test_support()
2863 .size_full()
2864 .overflow_hidden()
2865 .child(self.render_table_header(scrollable_cols.clone(), window, cx))
2866 .context_menu({
2867 let view = cx.entity();
2868 move |this, window: &mut Window, cx: &mut Context<PopupMenu>| {
2869 if let Some(row_ix) = view.read(cx).right_clicked_row {
2870 view.update(cx, |menu, cx| {
2871 menu.delegate_mut().context_menu(row_ix, this, window, cx)
2872 })
2873 } else {
2874 this
2875 }
2876 }
2877 })
2878 .map(|this| {
2879 if rows_count == 0 {
2880 this.children(empty_view)
2881 } else {
2882 this.child(
2883 h_flex().id("table-body").flex_grow_1().size_full().child(
2884 uniform_list(
2885 "table-uniform-list",
2886 render_rows_count,
2887 cx.processor(
2888 move |table, visible_range: Range<usize>, window, cx| {
2889 let col_sizes: Rc<Vec<gpui::Size<Pixels>>> = Rc::new(
2893 table
2894 .col_groups
2895 .get(scrollable_cols.clone())
2896 .unwrap_or_default()
2897 .iter()
2898 .map(|col| gpui::Size {
2899 width: col.width,
2900 height: px(0.),
2901 })
2902 .collect(),
2903 );
2904
2905 table.load_more_if_need(
2906 rows_count,
2907 visible_range.end,
2908 window,
2909 cx,
2910 );
2911 table.update_visible_range_if_need(
2912 visible_range.clone(),
2913 rows_count,
2914 Axis::Vertical,
2915 window,
2916 cx,
2917 );
2918
2919 if visible_range.start >= rows_count {
2920 table.scroll_to_row(rows_count.saturating_sub(1), cx);
2921 }
2922
2923 let mut items = Vec::with_capacity(
2924 visible_range.end.saturating_sub(visible_range.start),
2925 );
2926
2927 visible_range.for_each(|row_ix| {
2929 items.push(table.render_table_row(
2931 row_ix,
2932 rows_count,
2933 scrollable_cols.clone(),
2934 col_sizes.clone(),
2935 columns_count,
2936 is_filled,
2937 window,
2938 cx,
2939 ));
2940 });
2941
2942 items
2943 },
2944 ),
2945 )
2946 .flex_grow_1()
2947 .size_full()
2948 .with_sizing_behavior(ListSizingBehavior::Auto)
2949 .track_scroll(&self.vertical_scroll_handle)
2950 .map(|rows| {
2951 gpui_base::ScrollBounce::new(
2952 "table-scroll-bounce",
2953 &self.vertical_scroll_handle,
2954 rows,
2955 )
2956 .when_some(self.options.scroll_bounce, |bounce, on| {
2957 bounce.enabled(on)
2958 })
2959 })
2960 .into_any_element(),
2961 ),
2962 )
2963 }
2964 });
2965
2966 div()
2967 .size_full()
2968 .children(loading_view)
2969 .when(!loading, |this| {
2970 this.child(inner_table)
2971 .child(ScrollableMask::new(
2972 Axis::Horizontal,
2973 &self.horizontal_scroll_handle,
2974 ))
2975 .when(rows_count > 0, |this| {
2980 this.child(ScrollableMask::new(
2981 Axis::Vertical,
2982 &self.vertical_scroll_handle.0.borrow().base_handle,
2983 ))
2984 })
2985 .when(has_right_click, |this| {
2986 this.on_mouse_down_out(cx.listener(|this, e, window, cx| {
2987 this.on_row_right_click(e, None, window, cx);
2988 cx.notify();
2989 }))
2990 })
2991 })
2992 .on_prepaint({
2993 let state = cx.entity();
2994 move |bounds, _, cx| state.update(cx, |state, _| state.bounds = bounds)
2995 })
2996 .when(!window.is_inspector_picking(cx), |this| {
2997 this.child(
2998 div()
2999 .absolute()
3000 .top_0()
3001 .size_full()
3002 .when(self.options.scrollbar_visible.bottom, |this| {
3003 this.child(self.render_horizontal_scrollbar(window, cx))
3004 })
3005 .when(
3006 self.options.scrollbar_visible.right && rows_count > 0,
3007 |this| this.children(self.render_vertical_scrollbar(window, cx)),
3008 ),
3009 )
3010 })
3011 }
3012}
3013
3014#[cfg(test)]
3015mod tests {
3016 use gpui::{AnyView, App, Entity, StyleRefinement, TestAppContext};
3017
3018 use super::*;
3019
3020 struct WidthsDelegate;
3021
3022 struct BounceDelegate;
3023
3024 impl TableDelegate for BounceDelegate {
3025 fn columns_count(&self, _: &App) -> usize {
3026 1
3027 }
3028 fn rows_count(&self, _: &App) -> usize {
3029 40
3030 }
3031 fn column(&self, _: usize, _: &App) -> Column {
3032 Column::new("value", "Value")
3033 }
3034 fn render_td(
3035 &mut self,
3036 row: usize,
3037 _: usize,
3038 _: &mut Window,
3039 _: &mut Context<TableState<Self>>,
3040 ) -> impl IntoElement {
3041 div().child(row.to_string())
3042 }
3043 }
3044
3045 struct BounceTable(Entity<TableState<BounceDelegate>>);
3046
3047 impl Render for BounceTable {
3048 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3049 div()
3050 .w(px(240.))
3051 .h(px(200.))
3052 .child(DataTable::new(&self.0).scroll_bounce(true))
3053 }
3054 }
3055
3056 #[gpui::test]
3057 fn scroll_bounce_table_keeps_headers_fixed_and_accepts_new_wheel_input(
3058 cx: &mut TestAppContext,
3059 ) {
3060 cx.update(crate::init);
3061 let (view, cx) = cx.add_window_view(|window, cx| {
3062 BounceTable(cx.new(|cx| TableState::new(BounceDelegate, window, cx)))
3063 });
3064 cx.update(|window, cx| window.draw(cx).clear(cx));
3065 let state = view.read_with(cx, |view, _| view.0.clone());
3066 let header = state.read_with(cx, |state, _| state.col_groups[0].bounds);
3067 let wheel = |cx: &mut gpui::VisualTestContext, dy| {
3068 cx.simulate_event(gpui::ScrollEvent {
3069 position: gpui::point(px(100.), px(100.)),
3070 delta: gpui::ScrollDelta::Lines(gpui::point(0., dy)),
3071 ..Default::default()
3072 });
3073 };
3074 for (dy, phase) in [
3075 (-10000., gpui::TouchPhase::Started),
3076 (0., gpui::TouchPhase::Ended),
3077 ] {
3078 cx.simulate_event(gpui::ScrollEvent {
3079 position: gpui::point(px(100.), px(100.)),
3080 delta: gpui::ScrollDelta::Pixels(gpui::point(px(0.), px(dy))),
3081 touch_phase: phase,
3082 ..Default::default()
3083 });
3084 }
3085 cx.update(|window, cx| window.draw(cx).clear(cx));
3086 let end = state.read_with(cx, |state, _| {
3087 state
3088 .vertical_scroll_handle
3089 .0
3090 .borrow()
3091 .base_handle
3092 .offset()
3093 .y
3094 });
3095 assert!(end < px(0.));
3096 cx.executor().advance_clock(Duration::from_millis(200));
3097 cx.update(|window, cx| window.draw(cx).clear(cx));
3098 assert_eq!(
3099 state.read_with(cx, |state, _| state.col_groups[0].bounds),
3100 header
3101 );
3102 wheel(cx, 2.);
3103 assert!(
3104 state.read_with(cx, |state, _| state
3105 .vertical_scroll_handle
3106 .0
3107 .borrow()
3108 .base_handle
3109 .offset()
3110 .y)
3111 > end
3112 );
3113 }
3114
3115 #[gpui::test]
3116 fn programmatic_selection_keeps_the_viewport_but_keyboard_reveals(cx: &mut TestAppContext) {
3117 cx.update(crate::init);
3118 let (view, cx) = cx.add_window_view(|window, cx| {
3119 BounceTable(cx.new(|cx| TableState::new(BounceDelegate, window, cx)))
3120 });
3121 cx.update(|window, cx| window.draw(cx).clear(cx));
3122 let state = view.read_with(cx, |view, _| view.0.clone());
3123 let offset = |cx: &mut gpui::VisualTestContext| {
3124 state.read_with(cx, |state, _| {
3125 state
3126 .vertical_scroll_handle
3127 .0
3128 .borrow()
3129 .base_handle
3130 .offset()
3131 .y
3132 })
3133 };
3134
3135 state.update(cx, |state, cx| state.set_selected_row(0, cx));
3137 state.update(cx, |state, cx| state.scroll_to_row(39, cx));
3138 cx.update(|window, cx| window.draw(cx).clear(cx));
3139 let scrolled = offset(cx);
3140 assert!(scrolled < px(0.));
3141
3142 state.update(cx, |state, cx| state.set_selected_row(2, cx));
3144 cx.update(|window, cx| window.draw(cx).clear(cx));
3145 assert_eq!(offset(cx), scrolled);
3146 state.update(cx, |state, cx| state.set_selected_cell(1, 0, cx));
3147 cx.update(|window, cx| window.draw(cx).clear(cx));
3148 assert_eq!(offset(cx), scrolled);
3149 state.update(cx, |state, cx| {
3150 state.set_selection(TableSelection::Row(3), cx)
3151 });
3152 cx.update(|window, cx| window.draw(cx).clear(cx));
3153 assert_eq!(offset(cx), scrolled);
3154
3155 cx.update(|window, cx| {
3157 state.update(cx, |state, cx| {
3158 state.action_select_next(&SelectDown, window, cx)
3159 })
3160 });
3161 cx.update(|window, cx| window.draw(cx).clear(cx));
3162 assert_eq!(
3163 state.read_with(cx, |state, _| state.selected_row()),
3164 Some(4)
3165 );
3166 assert!(offset(cx) > scrolled);
3167 }
3168
3169 struct ThreeRowsDelegate;
3170
3171 impl TableDelegate for ThreeRowsDelegate {
3172 fn columns_count(&self, _: &App) -> usize {
3173 1
3174 }
3175 fn rows_count(&self, _: &App) -> usize {
3176 3
3177 }
3178 fn column(&self, _: usize, _: &App) -> Column {
3179 Column::new("value", "Value")
3180 }
3181 fn render_td(
3182 &mut self,
3183 row: usize,
3184 _: usize,
3185 _: &mut Window,
3186 _: &mut Context<TableState<Self>>,
3187 ) -> impl IntoElement {
3188 div().child(row.to_string())
3189 }
3190 }
3191
3192 struct StripedPanel {
3194 table: Entity<TableState<ThreeRowsDelegate>>,
3195 renders: usize,
3196 }
3197
3198 impl Render for StripedPanel {
3199 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3200 self.renders += 1;
3201 div()
3202 .size_full()
3203 .child(DataTable::new(&self.table).stripe(true))
3204 }
3205 }
3206
3207 struct CachedPanel(Entity<StripedPanel>);
3209
3210 impl Render for CachedPanel {
3211 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3212 div()
3213 .w(px(240.))
3214 .h(px(400.))
3215 .child(AnyView::from(self.0.clone()).cached(StyleRefinement::default().size_full()))
3216 }
3217 }
3218
3219 #[gpui::test]
3223 fn striped_table_with_few_rows_lets_a_cached_view_be_reused(cx: &mut TestAppContext) {
3224 cx.update(crate::init);
3225 let (view, cx) = cx.add_window_view(|window, cx| {
3226 let table = cx.new(|cx| TableState::new(ThreeRowsDelegate, window, cx));
3227 CachedPanel(cx.new(|_| StripedPanel { table, renders: 0 }))
3228 });
3229 let panel = view.read_with(cx, |view, _| view.0.clone());
3230 let table = panel.read_with(cx, |panel, _| panel.table.clone());
3231 let draw = |cx: &mut gpui::VisualTestContext| {
3232 cx.update(|window, cx| window.draw(cx).clear(cx));
3233 };
3234 draw(cx);
3235 table.update(cx, |_, cx| cx.notify());
3237 draw(cx);
3238 let renders = panel.read_with(cx, |panel, _| panel.renders);
3239 draw(cx);
3240 draw(cx);
3241 assert_eq!(panel.read_with(cx, |panel, _| panel.renders), renders);
3242 }
3243
3244 impl TableDelegate for WidthsDelegate {
3245 fn columns_count(&self, _: &App) -> usize {
3246 6
3247 }
3248
3249 fn rows_count(&self, _: &App) -> usize {
3250 0
3251 }
3252
3253 fn column(&self, col_ix: usize, _: &App) -> Column {
3254 match col_ix {
3255 0 => Column::new("narrow", "Narrow")
3256 .min_width(px(80.))
3257 .width(px(40.)),
3258 1 => Column::new("wide", "Wide")
3259 .max_width(px(120.))
3260 .width(px(300.)),
3261 2 => Column::new("tiny", "Tiny").width(px(10.)),
3263 3 => Column::new("wide_default", "Wide Default").width(px(2000.)),
3265 4 => Column::new("wide_explicit", "Wide Explicit")
3267 .max_width(px(2400.))
3268 .width(px(2000.)),
3269 _ => Column::new("inverted", "Inverted")
3271 .min_width(px(200.))
3272 .max_width(px(100.)),
3273 }
3274 }
3275
3276 fn render_td(
3277 &mut self,
3278 _: usize,
3279 _: usize,
3280 _: &mut Window,
3281 _: &mut Context<TableState<Self>>,
3282 ) -> impl IntoElement {
3283 div()
3284 }
3285 }
3286
3287 #[gpui::test]
3288 fn column_resize_bounds_preserve_initial_widths(cx: &mut TestAppContext) {
3289 cx.skip_drawing();
3290 let window = cx.add_window(|window, cx| TableState::new(WidthsDelegate, window, cx));
3291
3292 window
3293 .update(cx, |table, window, cx| {
3294 let widths = |table: &TableState<WidthsDelegate>| {
3295 table
3296 .col_groups
3297 .iter()
3298 .map(|col_group| col_group.width)
3299 .collect::<Vec<_>>()
3300 };
3301 assert_eq!(
3302 widths(table),
3303 [px(40.), px(300.), px(10.), px(2000.), px(2000.), px(100.)]
3304 );
3305
3306 for ix in 0..table.col_groups.len() {
3307 table.resize_cols(ix, px(10000.), window, cx);
3308 }
3309 assert_eq!(
3310 widths(table),
3311 [
3312 px(1200.),
3313 px(120.),
3314 px(1200.),
3315 px(1200.),
3316 px(2400.),
3317 px(100.)
3318 ]
3319 );
3320
3321 for ix in 0..table.col_groups.len() {
3322 table.resize_cols(ix, px(-100.), window, cx);
3323 }
3324 assert_eq!(
3325 widths(table),
3326 [px(80.), px(20.), px(20.), px(20.), px(20.), px(100.)]
3327 );
3328 })
3329 .unwrap();
3330 }
3331}