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>) {
545 let is_down = match self.selected_row {
546 Some(selected_row) => row_ix > selected_row,
547 None => true,
548 };
549
550 self.selection_mode = SelectionMode::Row;
551 self.right_clicked_row = None;
552 self.selected_row = Some(row_ix);
553 if let Some(row_ix) = self.selected_row {
554 self.vertical_scroll_handle.scroll_to_item(
555 row_ix,
556 if is_down {
557 ScrollStrategy::Bottom
558 } else {
559 ScrollStrategy::Top
560 },
561 );
562 }
563 cx.emit(TableEvent::SelectRow(row_ix));
564 cx.emit(TableEvent::RightClickedRow(None));
565 cx.notify();
566 }
567
568 pub fn right_clicked_row(&self) -> Option<usize> {
570 self.right_clicked_row
571 }
572
573 pub fn right_clicked_cell(&self) -> Option<(usize, usize)> {
575 self.right_clicked_cell
576 }
577
578 pub fn set_right_clicked_row(&mut self, row: Option<usize>, cx: &mut Context<Self>) {
583 self.right_clicked_row = row;
584 cx.notify();
585 }
586
587 pub fn selected_col(&self) -> Option<usize> {
592 self.selected_col
593 .filter(|_| self.selection_mode.is_column())
594 }
595
596 pub fn set_selected_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
598 self.selection_mode = SelectionMode::Column;
599 self.selected_col = Some(col_ix);
600 if let Some(col_ix) = self.selected_col {
601 self.scroll_to_col(col_ix, cx);
602 }
603 cx.emit(TableEvent::SelectColumn(col_ix));
604 cx.notify();
605 }
606
607 pub fn selected_cell(&self) -> Option<(usize, usize)> {
619 self.selected_cell.filter(|_| self.selection_mode.is_cell())
620 }
621
622 pub fn set_selected_cell(&mut self, row_ix: usize, col_ix: usize, cx: &mut Context<Self>) {
638 self.selection_mode = SelectionMode::Cell;
639 self.selected_cell = Some((row_ix, col_ix));
640 self.right_clicked_cell = None;
641
642 self.vertical_scroll_handle
644 .scroll_to_item(row_ix, ScrollStrategy::Center);
645 self.scroll_to_col(col_ix, cx);
646
647 cx.emit(TableEvent::SelectCell(row_ix, col_ix));
648 cx.notify();
649 }
650
651 pub fn set_selection(&mut self, selection: TableSelection, cx: &mut Context<Self>) {
656 match selection {
657 TableSelection::None => self.clear_selection(cx),
658 TableSelection::Row(row_ix) => self.set_selected_row(row_ix, cx),
659 TableSelection::Column(col_ix) => self.set_selected_col(col_ix, cx),
660 TableSelection::Cell(row_ix, col_ix) => self.set_selected_cell(row_ix, col_ix, cx),
661 }
662 }
663
664 pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
666 self.selection_mode = SelectionMode::Row;
667 self.selected_row = None;
668 self.selected_col = None;
669 self.selected_cell = None;
670 cx.emit(TableEvent::ClearSelection);
671 cx.notify();
672 }
673
674 pub fn visible_range(&self) -> &TableVisibleRange {
678 &self.visible_range
679 }
680
681 pub fn headers(&self, cx: &App) -> Vec<String> {
686 let columns_count = self.delegate.columns_count(cx);
687 let mut headers = Vec::with_capacity(columns_count);
688 for col_ix in 0..columns_count {
689 let column = self.delegate.column(col_ix, cx);
690 headers.push(column.name.to_string());
691 }
692
693 headers
694 }
695
696 pub fn dump(&self, cx: &App) -> (Vec<String>, Vec<Vec<String>>) {
703 self.dump_range(0..self.delegate.rows_count(cx), cx)
704 }
705
706 pub fn dump_range(&self, range: Range<usize>, cx: &App) -> (Vec<String>, Vec<Vec<String>>) {
714 let columns_count = self.delegate.columns_count(cx);
715 let rows_count = self.delegate.rows_count(cx);
716 let start = range.start.min(rows_count);
717 let end = range.end.min(rows_count).max(start);
718
719 let mut rows = Vec::with_capacity(end - start);
720 for row_ix in start..end {
721 let mut row = Vec::with_capacity(columns_count);
722 for col_ix in 0..columns_count {
723 row.push(self.delegate.cell_text(row_ix, col_ix, cx));
724 }
725 rows.push(row);
726 }
727
728 (self.headers(cx), rows)
729 }
730
731 pub fn refresh_header_layout(&mut self, cx: &mut Context<Self>) {
735 self.update_header_layout(cx);
736 cx.notify();
737 }
738
739 fn prepare_col_groups(&mut self, cx: &mut Context<Self>) {
740 self.col_groups = (0..self.delegate.columns_count(cx))
741 .map(|col_ix| {
742 let column = self.delegate().column(col_ix, cx);
743 ColGroup {
744 width: column.width,
745 bounds: Bounds::default(),
746 column,
747 }
748 })
749 .collect();
750
751 self.update_header_layout(cx);
752 }
753
754 fn update_header_layout(&mut self, cx: &mut Context<Self>) {
755 let group_rows = self.delegate.group_headers(cx);
756
757 let mut layout = match group_rows.as_ref() {
758 Some(rows) => Vec::with_capacity(rows.len() + 1),
759 None => Vec::with_capacity(1),
760 };
761
762 if let Some(group_rows) = group_rows {
763 for row in group_rows {
764 let mut cell_row = Vec::with_capacity(row.len());
765 let mut current_leaf_ix = 0;
766 for group in row {
767 let mut width = px(0.);
768 let start_leaf_col_ix = current_leaf_ix;
769 for i in 0..group.span {
770 if current_leaf_ix + i < self.col_groups.len() {
771 width += self.col_groups[current_leaf_ix + i].width;
772 }
773 }
774 current_leaf_ix += group.span;
775 cell_row.push(HeaderCell {
776 label: group.label.clone(),
777 width,
778 col_span: group.span,
779 is_leaf: false,
780 leaf_col_ix: None,
781 start_leaf_col_ix,
782 });
783 }
784 layout.push(cell_row);
785 }
786 }
787
788 let mut leaf_row = Vec::with_capacity(self.col_groups.len());
789 for (ix, group) in self.col_groups.iter().enumerate() {
790 leaf_row.push(HeaderCell {
791 label: group.column.name.clone(),
792 width: group.width,
793 col_span: 1,
794 is_leaf: true,
795 leaf_col_ix: Some(ix),
796 start_leaf_col_ix: ix,
797 });
798 }
799 layout.push(leaf_row);
800
801 self.header_layout = layout;
802 }
803
804 fn fixed_cols_count(&self, side: ColumnFixed) -> usize {
805 if !self.col_fixed {
806 return 0;
807 }
808
809 self.col_groups
810 .iter()
811 .filter(|col| col.column.fixed == Some(side))
812 .count()
813 }
814
815 fn scrollable_cols(&self) -> Range<usize> {
821 let total = self.col_groups.len();
822 let left = self.fixed_cols_count(ColumnFixed::Left).min(total);
823 let right = self.fixed_cols_count(ColumnFixed::Right).min(total - left);
824 left..total - right
825 }
826
827 fn col_fixed_side(&self, col_ix: usize) -> Option<ColumnFixed> {
829 let scrollable_cols = self.scrollable_cols();
830 if col_ix < scrollable_cols.start {
831 Some(ColumnFixed::Left)
832 } else if col_ix >= scrollable_cols.end {
833 Some(ColumnFixed::Right)
834 } else {
835 None
836 }
837 }
838
839 fn header_row_height(&self) -> Pixels {
841 self.options
842 .header_row_height
843 .unwrap_or(self.options.size.table_row_height())
844 }
845
846 fn header_band_height(&self) -> Pixels {
849 self.header_row_height() * self.header_layout.len().max(1) as f32
850 }
851
852 fn page_item_count(&self) -> usize {
853 let row_height = self.options.size.table_row_height();
854 let body_height = (self.bounds.size.height - self.header_band_height()).max(px(0.));
855 let count = (body_height / row_height).floor() as usize;
856 count.max(1)
857 }
858
859 fn on_row_right_click(
860 &mut self,
861 _: &MouseDownEvent,
862 row_ix: Option<usize>,
863 _: &mut Window,
864 cx: &mut Context<Self>,
865 ) {
866 self.right_clicked_row = row_ix;
867 self.right_clicked_cell = None;
868 cx.emit(TableEvent::RightClickedRow(row_ix));
869 }
870
871 fn on_cell_right_click(
872 &mut self,
873 _: &MouseDownEvent,
874 row_ix: usize,
875 col_ix: usize,
876 _: &mut Window,
877 cx: &mut Context<Self>,
878 ) {
879 if !self.cell_selectable {
880 return;
881 }
882
883 cx.stop_propagation();
884 self.right_clicked_cell = Some((row_ix, col_ix));
885 self.right_clicked_row = None;
886 cx.emit(TableEvent::RightClickedCell(row_ix, col_ix));
887 }
888
889 fn on_row_left_click(
890 &mut self,
891 e: &ClickEvent,
892 row_ix: usize,
893 _: &mut Window,
894 cx: &mut Context<Self>,
895 ) {
896 if !self.row_selectable {
897 return;
898 }
899
900 cx.stop_propagation();
901 if self.selects_row_on_click(e, cx) {
902 self.set_selected_row(row_ix, cx);
903 }
904
905 if e.click_count() == 2 {
906 cx.emit(TableEvent::DoubleClickedRow(row_ix));
907 }
908 }
909
910 fn selects_row_on_click(&self, e: &ClickEvent, cx: &App) -> bool {
912 let modifiers = e.modifiers();
913 self.select_on_modifier_click || !(modifiers.secondary(cx) || modifiers.shift)
914 }
915
916 fn on_col_head_click(&mut self, col_ix: usize, _: &mut Window, cx: &mut Context<Self>) {
917 if !self.col_selectable {
918 return;
919 }
920
921 let Some(col_group) = self.col_groups.get(col_ix) else {
922 return;
923 };
924
925 if !col_group.column.selectable {
926 return;
927 }
928
929 self.set_selected_col(col_ix, cx)
930 }
931
932 fn on_cell_click(
933 &mut self,
934 e: &ClickEvent,
935 row_ix: usize,
936 col_ix: usize,
937 _: &mut Window,
938 cx: &mut Context<Self>,
939 ) {
940 if !self.cell_selectable {
941 return;
942 }
943
944 cx.stop_propagation();
945
946 let is_double_click = e.click_count() == 2;
947
948 let is_reselect = self.selected_cell() == Some((row_ix, col_ix));
954 let should_escalate_to_row = !self.row_header
955 && self.row_selectable
956 && is_reselect
957 && !is_double_click
958 && self.selects_row_on_click(e, cx);
959 if should_escalate_to_row {
960 self.set_selected_row(row_ix, cx);
961 return;
962 }
963
964 self.set_selected_cell(row_ix, col_ix, cx);
965
966 if is_double_click {
967 cx.emit(TableEvent::DoubleClickedCell(row_ix, col_ix));
968 }
969 }
970
971 fn has_selection(&self) -> bool {
972 self.selection() != TableSelection::None
973 }
974
975 pub(super) fn action_cancel(&mut self, _: &Cancel, _: &mut Window, cx: &mut Context<Self>) {
976 if self.has_selection() {
977 self.clear_selection(cx);
978 return;
979 }
980 cx.propagate();
981 }
982
983 pub(super) fn action_select_prev(
984 &mut self,
985 _: &SelectUp,
986 _: &mut Window,
987 cx: &mut Context<Self>,
988 ) {
989 let rows_count = self.delegate.rows_count(cx);
990 if rows_count < 1 {
991 return;
992 }
993
994 if self.selection_mode.is_cell() {
996 if let Some((row_ix, col_ix)) = self.selected_cell {
997 let new_row = if row_ix > 0 {
998 row_ix.saturating_sub(1)
999 } else if self.loop_selection {
1000 rows_count.saturating_sub(1)
1001 } else {
1002 row_ix
1003 };
1004 self.set_selected_cell(new_row, col_ix, cx);
1005 } else {
1006 self.set_selected_cell(0, 0, cx);
1008 }
1009 return;
1010 }
1011
1012 if !self.row_selectable {
1014 return;
1015 }
1016 let mut selected_row = self.selected_row.unwrap_or(0);
1017 if selected_row > 0 {
1018 selected_row = selected_row.saturating_sub(1);
1019 } else {
1020 if self.loop_selection {
1021 selected_row = rows_count.saturating_sub(1);
1022 }
1023 }
1024
1025 self.set_selected_row(selected_row, cx);
1026 }
1027
1028 pub(super) fn action_select_next(
1029 &mut self,
1030 _: &SelectDown,
1031 _: &mut Window,
1032 cx: &mut Context<Self>,
1033 ) {
1034 let rows_count = self.delegate.rows_count(cx);
1035 if rows_count < 1 {
1036 return;
1037 }
1038
1039 if self.selection_mode.is_cell() {
1041 if let Some((row_ix, col_ix)) = self.selected_cell {
1042 let new_row = if row_ix < rows_count.saturating_sub(1) {
1043 row_ix + 1
1044 } else if self.loop_selection {
1045 0
1046 } else {
1047 row_ix
1048 };
1049 self.set_selected_cell(new_row, col_ix, cx);
1050 } else {
1051 self.set_selected_cell(0, 0, cx);
1053 }
1054 return;
1055 }
1056
1057 if !self.row_selectable {
1059 return;
1060 }
1061 let selected_row = match self.selected_row {
1062 Some(selected_row) if selected_row < rows_count.saturating_sub(1) => selected_row + 1,
1063 Some(selected_row) => {
1064 if self.loop_selection {
1065 0
1066 } else {
1067 selected_row
1068 }
1069 }
1070 _ => 0,
1071 };
1072
1073 self.set_selected_row(selected_row, cx);
1074 }
1075
1076 pub(super) fn action_select_first_column(
1077 &mut self,
1078 _: &SelectFirst,
1079 _: &mut Window,
1080 cx: &mut Context<Self>,
1081 ) {
1082 if self.selection_mode.is_cell() {
1084 if let Some((row_ix, _)) = self.selected_cell {
1085 self.set_selected_cell(row_ix, 0, cx);
1086 } else {
1087 self.set_selected_cell(0, 0, cx);
1089 }
1090 return;
1091 }
1092
1093 if self.selection_mode.is_row() && self.row_selectable {
1095 if self.delegate.rows_count(cx) > 0 {
1096 self.set_selected_row(0, cx);
1097 }
1098 return;
1099 }
1100
1101 self.set_selected_col(0, cx);
1103 }
1104
1105 pub(super) fn action_select_last_column(
1106 &mut self,
1107 _: &SelectLast,
1108 _: &mut Window,
1109 cx: &mut Context<Self>,
1110 ) {
1111 let columns_count = self.delegate.columns_count(cx);
1112
1113 if self.selection_mode.is_cell() {
1115 if let Some((row_ix, _)) = self.selected_cell {
1116 self.set_selected_cell(row_ix, columns_count.saturating_sub(1), cx);
1117 } else {
1118 self.set_selected_cell(0, columns_count.saturating_sub(1), cx);
1120 }
1121 return;
1122 }
1123
1124 if self.selection_mode.is_row() && self.row_selectable {
1126 let rows_count = self.delegate.rows_count(cx);
1127 if rows_count > 0 {
1128 self.set_selected_row(rows_count - 1, cx);
1129 }
1130 return;
1131 }
1132
1133 self.set_selected_col(columns_count.saturating_sub(1), cx);
1135 }
1136
1137 pub(super) fn action_select_page_up(
1138 &mut self,
1139 _: &SelectPageUp,
1140 _: &mut Window,
1141 cx: &mut Context<Self>,
1142 ) {
1143 let step = self.page_item_count();
1144
1145 if self.selection_mode.is_cell() {
1147 if let Some((row_ix, col_ix)) = self.selected_cell {
1148 let target = row_ix.saturating_sub(step);
1149 self.set_selected_cell(target, col_ix, cx);
1150 } else {
1151 self.set_selected_cell(0, 0, cx);
1153 }
1154 return;
1155 }
1156
1157 if !self.row_selectable {
1159 return;
1160 }
1161 let current = self.selected_row.unwrap_or(0);
1162 let target = current.saturating_sub(step);
1163 self.set_selected_row(target, cx);
1164 }
1165
1166 pub(super) fn action_select_page_down(
1167 &mut self,
1168 _: &SelectPageDown,
1169 _: &mut Window,
1170 cx: &mut Context<Self>,
1171 ) {
1172 let rows_count = self.delegate.rows_count(cx);
1173 if rows_count == 0 {
1174 return;
1175 }
1176
1177 let step = self.page_item_count();
1178
1179 if self.selection_mode.is_cell() {
1181 if let Some((row_ix, col_ix)) = self.selected_cell {
1182 let max_row = rows_count.saturating_sub(1);
1183 let target = (row_ix + step).min(max_row);
1184 self.set_selected_cell(target, col_ix, cx);
1185 } else {
1186 self.set_selected_cell(0, 0, cx);
1188 }
1189 return;
1190 }
1191
1192 if !self.row_selectable {
1194 return;
1195 }
1196 let current = self.selected_row.unwrap_or(0);
1197 let max_row = rows_count.saturating_sub(1);
1198 let target = (current + step).min(max_row);
1199 self.set_selected_row(target, cx);
1200 }
1201
1202 pub(super) fn action_select_prev_col(
1203 &mut self,
1204 _: &SelectPrevColumn,
1205 _: &mut Window,
1206 cx: &mut Context<Self>,
1207 ) {
1208 let columns_count = self.delegate.columns_count(cx);
1209
1210 if self.selection_mode.is_cell() {
1212 if let Some((row_ix, col_ix)) = self.selected_cell {
1213 let new_col = if col_ix > 0 {
1214 col_ix.saturating_sub(1)
1215 } else if self.loop_selection {
1216 columns_count.saturating_sub(1)
1217 } else {
1218 col_ix
1219 };
1220 self.set_selected_cell(row_ix, new_col, cx);
1221 } else {
1222 self.set_selected_cell(0, 0, cx);
1224 }
1225 return;
1226 }
1227
1228 let mut selected_col = self.selected_col.unwrap_or(0);
1230 if selected_col > 0 {
1231 selected_col = selected_col.saturating_sub(1);
1232 } else {
1233 if self.loop_selection {
1234 selected_col = columns_count.saturating_sub(1);
1235 }
1236 }
1237 self.set_selected_col(selected_col, cx);
1238 }
1239
1240 pub(super) fn action_select_next_col(
1241 &mut self,
1242 _: &SelectNextColumn,
1243 _: &mut Window,
1244 cx: &mut Context<Self>,
1245 ) {
1246 let columns_count = self.delegate.columns_count(cx);
1247
1248 if self.selection_mode.is_cell() {
1250 if let Some((row_ix, col_ix)) = self.selected_cell {
1251 let new_col = if col_ix < columns_count.saturating_sub(1) {
1252 col_ix + 1
1253 } else if self.loop_selection {
1254 0
1255 } else {
1256 col_ix
1257 };
1258 self.set_selected_cell(row_ix, new_col, cx);
1259 } else {
1260 self.set_selected_cell(0, 0, cx);
1262 }
1263 return;
1264 }
1265
1266 let mut selected_col = self.selected_col.unwrap_or(0);
1268 if selected_col < columns_count.saturating_sub(1) {
1269 selected_col += 1;
1270 } else {
1271 if self.loop_selection {
1272 selected_col = 0;
1273 }
1274 }
1275
1276 self.set_selected_col(selected_col, cx);
1277 }
1278
1279 fn scroll_table_by_col_resizing(
1281 &mut self,
1282 mouse_position: Point<Pixels>,
1283 col_group: &ColGroup,
1284 ) {
1285 if mouse_position.x > self.bounds.right() {
1287 return;
1288 }
1289
1290 let mut offset = self.horizontal_scroll_handle.offset();
1291 let col_bounds = col_group.bounds;
1292
1293 if mouse_position.x < self.bounds.left()
1294 && col_bounds.right() < self.bounds.left() + px(20.)
1295 {
1296 offset.x += px(1.);
1297 } else if mouse_position.x > self.bounds.right()
1298 && col_bounds.right() > self.bounds.right() - px(20.)
1299 {
1300 offset.x -= px(1.);
1301 }
1302
1303 self.horizontal_scroll_handle.set_offset(offset);
1304 }
1305
1306 pub fn col_width(&self, col_ix: usize) -> Option<Pixels> {
1313 self.col_groups.get(col_ix).map(|group| group.width)
1314 }
1315
1316 pub fn fit_col(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) -> bool {
1325 if !self.is_col_resizable(col_ix) {
1326 return false;
1327 }
1328 let Some(content) = self.delegate.fit_column(col_ix, window, cx) else {
1329 return false;
1330 };
1331 let padding = self
1332 .col_groups
1333 .get(col_ix)
1334 .and_then(|group| group.column.paddings)
1335 .unwrap_or_else(|| self.options.size.table_cell_padding());
1336 let scale_factor = window.scale_factor();
1340 let device_pixels = |length: Pixels| (f32::from(length) * scale_factor).ceil();
1341 let mut content_pixels = device_pixels(content);
1342 if px(content_pixels / scale_factor) < content {
1345 content_pixels += 1.;
1346 }
1347 let width = content_pixels + device_pixels(padding.left) + device_pixels(padding.right);
1348 if self.resize_cols(col_ix, px(width / scale_factor), window, cx) {
1349 let new_widths = self.col_groups.iter().map(|g| g.width).collect();
1350 cx.emit(TableEvent::ColumnWidthsChanged(new_widths));
1351 }
1352 true
1353 }
1354
1355 fn resize_cols(
1360 &mut self,
1361 ix: usize,
1362 size: Pixels,
1363 _: &mut Window,
1364 cx: &mut Context<Self>,
1365 ) -> bool {
1366 if !self.col_resizable {
1367 return false;
1368 }
1369
1370 let mut changed = false;
1371 if let Some(col_group) = self.col_groups.get_mut(ix) {
1372 if col_group.is_resizable() {
1373 let new_width = size
1374 .max(col_group.column.min_width)
1375 .min(col_group.column.max_width);
1376 if col_group.width != new_width {
1377 col_group.width = new_width;
1378 changed = true;
1379 }
1380 }
1381 }
1382
1383 if changed {
1384 self.update_header_layout(cx);
1385 cx.notify();
1386 }
1387 changed
1388 }
1389
1390 fn perform_sort(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
1391 if !self.sortable {
1392 return;
1393 }
1394
1395 let sort = self.col_groups.get(col_ix).and_then(|g| g.column.sort);
1396 if sort.is_none() {
1397 return;
1398 }
1399
1400 let sort = sort.unwrap();
1401 let sort = match sort {
1402 ColumnSort::Ascending => ColumnSort::Default,
1403 ColumnSort::Descending => ColumnSort::Ascending,
1404 ColumnSort::Default => ColumnSort::Descending,
1405 };
1406
1407 for (ix, col_group) in self.col_groups.iter_mut().enumerate() {
1408 if ix == col_ix {
1409 col_group.column.sort = Some(sort);
1410 } else {
1411 if col_group.column.sort.is_some() {
1412 col_group.column.sort = Some(ColumnSort::Default);
1413 }
1414 }
1415 }
1416
1417 self.delegate_mut().perform_sort(col_ix, sort, window, cx);
1418
1419 cx.notify();
1420 }
1421
1422 fn move_column(
1423 &mut self,
1424 col_ix: usize,
1425 to_ix: usize,
1426 window: &mut Window,
1427 cx: &mut Context<Self>,
1428 ) {
1429 if col_ix == to_ix {
1430 return;
1431 }
1432
1433 self.delegate.move_column(col_ix, to_ix, window, cx);
1434 let col_group = self.col_groups.remove(col_ix);
1435 self.col_groups.insert(to_ix, col_group);
1436
1437 cx.emit(TableEvent::MoveColumn(col_ix, to_ix));
1438 cx.notify();
1439 }
1440
1441 fn drag_gap_at(&self, x: Pixels, drag_col_ix: usize) -> Option<usize> {
1445 let scrollable_cols = self.scrollable_cols();
1446
1447 let pointer_side = if scrollable_cols.start > 0 && x < self.fixed_head_cols_bounds.right() {
1452 Some(ColumnFixed::Left)
1453 } else if scrollable_cols.end < self.col_groups.len()
1454 && x >= self.fixed_right_head_cols_bounds.left()
1455 {
1456 Some(ColumnFixed::Right)
1457 } else {
1458 None
1459 };
1460 if self.col_fixed_side(drag_col_ix) != pointer_side {
1461 return None;
1462 }
1463
1464 let candidates = match pointer_side {
1468 Some(ColumnFixed::Left) => 0..scrollable_cols.start,
1469 Some(ColumnFixed::Right) => scrollable_cols.end..self.col_groups.len(),
1470 None => self.calculate_visible_leaf_col_range(scrollable_cols).0,
1471 };
1472
1473 let mut gap = candidates.start;
1475 for ix in candidates {
1476 if x < self.col_groups[ix].bounds.center().x {
1477 break;
1478 }
1479 gap = ix + 1;
1480 }
1481
1482 if gap == drag_col_ix || gap == drag_col_ix + 1 {
1485 None
1486 } else {
1487 Some(gap)
1488 }
1489 }
1490
1491 fn load_more_if_need(
1493 &mut self,
1494 rows_count: usize,
1495 visible_end: usize,
1496 window: &mut Window,
1497 cx: &mut Context<Self>,
1498 ) {
1499 let threshold = self.delegate.load_more_threshold();
1500 if visible_end >= rows_count.saturating_sub(threshold) {
1502 if !self.delegate.has_more(cx) {
1503 return;
1504 }
1505
1506 self._load_more_task = cx.spawn_in(window, async move |view, window| {
1507 _ = view.update_in(window, |view, window, cx| {
1508 view.delegate.load_more(window, cx);
1509 });
1510 });
1511 }
1512 }
1513
1514 fn update_visible_range_if_need(
1515 &mut self,
1516 visible_range: Range<usize>,
1517 items_count: usize,
1518 axis: Axis,
1519 window: &mut Window,
1520 cx: &mut Context<Self>,
1521 ) {
1522 if visible_range.len() <= 1 && items_count > 1 {
1525 return;
1526 }
1527
1528 let end = visible_range.end.min(items_count);
1530 let visible_range = visible_range.start.min(end)..end;
1531 if visible_range.is_empty() && items_count > 0 {
1533 return;
1534 }
1535
1536 if axis == Axis::Vertical {
1537 if self.visible_range.rows == visible_range {
1538 return;
1539 }
1540 self.delegate_mut()
1541 .visible_rows_changed(visible_range.clone(), window, cx);
1542 self.visible_range.rows = visible_range;
1543 } else {
1544 if self.visible_range.cols == visible_range {
1545 return;
1546 }
1547 self.delegate_mut()
1548 .visible_columns_changed(visible_range.clone(), window, cx);
1549 self.visible_range.cols = visible_range;
1550 }
1551 }
1552
1553 fn render_cell(
1554 &self,
1555 _row_ix: Option<usize>,
1556 col_ix: usize,
1557 _window: &mut Window,
1558 cx: &mut Context<Self>,
1559 ) -> Div {
1560 let Some(col_group) = self.col_groups.get(col_ix) else {
1561 return div();
1562 };
1563 let is_rtl = gpui_base::LayoutDirection::global(cx).is_rtl();
1564
1565 let col_width = col_group.width;
1566 let col_padding = col_group.column.paddings;
1567
1568 div()
1569 .w(col_width)
1570 .h_full()
1571 .flex_shrink_0()
1572 .overflow_hidden()
1573 .whitespace_nowrap()
1574 .table_cell_size(self.options.size)
1575 .map(|this| match (col_group.column.align, is_rtl) {
1579 (TextAlign::Center, _) => this.text_center(),
1580 (TextAlign::Right, false) | (TextAlign::Left, true) => this.text_right(),
1581 (TextAlign::Right, true) => this.text_left(),
1582 _ => this,
1583 })
1584 .map(|this| match col_padding {
1585 Some(padding) => this
1586 .pl(padding.left)
1587 .pr(padding.right)
1588 .pt(padding.top)
1589 .pb(padding.bottom),
1590 None => this,
1591 })
1592 }
1593
1594 fn a11y_cell<E>(&self, cell: E, row_ix: usize, col_ix: usize, window: &Window, cx: &App) -> E
1600 where
1601 E: gpui::StatefulInteractiveElement + FluentBuilder,
1602 {
1603 let cell = if self.cell_selectable {
1604 let is_selected = self.selected_cell() == Some((row_ix, col_ix));
1605 cell.role(gpui::Role::GridCell)
1606 .aria_selected(is_selected)
1607 .when(
1610 is_selected && self.focus_handle.is_focused(window),
1611 |this| this.aria_active_descendant(),
1612 )
1613 } else {
1614 cell.role(gpui::Role::Cell)
1615 };
1616 let label = if window.is_a11y_active() || cfg!(feature = "test-support") {
1620 self.delegate.cell_label(row_ix, col_ix, cx)
1621 } else {
1622 None
1623 };
1624 cell.aria_column_index(col_ix)
1625 .when_some(label, |this, label| this.aria_label(label))
1626 }
1627
1628 fn render_col_wrap(
1631 &self,
1632 _row_ix: Option<usize>,
1633 col_ix: usize,
1634 _: &mut Window,
1635 cx: &mut Context<Self>,
1636 ) -> Div {
1637 let el = h_flex().h_full();
1638 let selectable = self.col_selectable
1639 && self
1640 .col_groups
1641 .get(col_ix)
1642 .map(|col_group| col_group.column.selectable)
1643 .unwrap_or(false);
1644
1645 if selectable && self.selected_col() == Some(col_ix) {
1648 el.bg(cx.theme().tokens.table_active)
1649 } else {
1650 el
1651 }
1652 }
1653
1654 fn render_leading_resize_handle(
1661 &self,
1662 ix: usize,
1663 _: &mut Window,
1664 cx: &mut Context<Self>,
1665 ) -> impl IntoElement {
1666 let is_fixed_right = |ix: usize| {
1670 self.col_fixed
1671 && self.col_groups.get(ix).and_then(|col| col.column.fixed)
1672 == Some(ColumnFixed::Right)
1673 };
1674 let Some(prev) = ix.checked_sub(1).filter(|prev| {
1675 self.is_col_resizable(*prev) && (!is_fixed_right(ix) || is_fixed_right(*prev))
1676 }) else {
1677 return div().into_any_element();
1678 };
1679
1680 self.resize_handle_band(prev, ("resizable-handle-leading", ix).into(), cx)
1681 .absolute()
1682 .top_0()
1683 .left_0()
1684 .h_full()
1685 .w(HANDLE_PADDING)
1686 .into_any_element()
1687 }
1688
1689 fn render_resize_handle(
1697 &self,
1698 ix: usize,
1699 _: &mut Window,
1700 cx: &mut Context<Self>,
1701 ) -> impl IntoElement {
1702 if !self.is_col_resizable(ix) {
1703 return div().into_any_element();
1704 }
1705
1706 let group_id = SharedString::from(format!("resizable-handle:{}", ix));
1707
1708 self.resize_handle_band(ix, ("resizable-handle", ix).into(), cx)
1709 .group(group_id.clone())
1710 .h_full()
1711 .w(HANDLE_PADDING)
1712 .ml(-HANDLE_PADDING)
1713 .justify_end()
1714 .items_center()
1715 .child(
1716 div()
1717 .h_full()
1718 .justify_center()
1719 .bg(cx.theme().table_row_border)
1720 .group_hover(&group_id, |this| this.bg(cx.theme().border).h_full())
1721 .w(px(1.)),
1722 )
1723 .into_any_element()
1724 }
1725
1726 fn is_col_resizable(&self, ix: usize) -> bool {
1727 self.col_resizable
1728 && self
1729 .col_groups
1730 .get(ix)
1731 .map(|col| col.is_resizable())
1732 .unwrap_or(false)
1733 }
1734
1735 fn resize_handle_band(
1745 &self,
1746 ix: usize,
1747 id: ElementId,
1748 cx: &mut Context<Self>,
1749 ) -> Stateful<Div> {
1750 h_flex()
1751 .id(id)
1752 .occlude()
1753 .cursor_col_resize()
1754 .on_drag_move(
1755 cx.listener(move |view, e: &DragMoveEvent<ResizeColumn>, window, cx| {
1756 match e.drag(cx) {
1757 ResizeColumn((entity_id, ix)) => {
1758 if cx.entity_id() != *entity_id {
1759 return;
1760 }
1761
1762 let ix = *ix;
1769 if view.fitted_col == Some(ix) {
1770 return;
1771 }
1772 view.resizing_col = Some(ix);
1773
1774 let col_group = view
1775 .col_groups
1776 .get(ix)
1777 .expect("BUG: invalid col index")
1778 .clone();
1779
1780 let Some(origin) = view.resize_origin else {
1786 return;
1787 };
1788 view.resize_cols(
1789 ix,
1790 origin.width + (e.event.position.x - origin.x),
1791 window,
1792 cx,
1793 );
1794
1795 view.scroll_table_by_col_resizing(e.event.position, &col_group);
1797 }
1798 };
1799 }),
1800 )
1801 .on_drag(ResizeColumn((cx.entity_id(), ix)), |drag, _, _, cx| {
1802 cx.stop_propagation();
1803 cx.new(|_| drag.clone())
1804 })
1805 .on_mouse_down(
1806 MouseButton::Left,
1807 cx.listener(move |view, e: &MouseDownEvent, window, cx| {
1808 view.resize_origin = view.col_groups.get(ix).map(|col_group| ResizeOrigin {
1809 x: e.position.x,
1810 width: col_group.width,
1811 });
1812 if e.click_count == 1 {
1813 view.fitted_col = None;
1814 } else if e.click_count == 2 && view.fit_col(ix, window, cx) {
1815 view.fitted_col = Some(ix);
1816 }
1817 }),
1818 )
1819 .on_mouse_up_out(
1820 MouseButton::Left,
1821 cx.listener(|view, _, _, cx| {
1822 view.resize_origin = None;
1823 if view.resizing_col.is_none() {
1824 return;
1825 }
1826
1827 view.resizing_col = None;
1828
1829 let new_widths = view.col_groups.iter().map(|g| g.width).collect();
1830 cx.emit(TableEvent::ColumnWidthsChanged(new_widths));
1831 cx.notify();
1832 }),
1833 )
1834 }
1835
1836 fn render_fixed_cols_border(&self, side: ColumnFixed, cx: &App) -> Option<Div> {
1839 self.options.fixed_cols_border.then(|| {
1840 div()
1841 .absolute()
1842 .top_0()
1843 .bottom_0()
1844 .w_0()
1845 .flex_shrink_0()
1846 .border_color(cx.theme().border)
1847 .map(|this| match side {
1848 ColumnFixed::Left => this.right_0().border_r_1(),
1849 ColumnFixed::Right => this.left_0().border_l_1(),
1850 })
1851 })
1852 }
1853
1854 fn render_row_header_cell(
1856 &self,
1857 row_ix: usize,
1858 is_head: bool,
1859 cx: &mut Context<Self>,
1860 ) -> impl IntoElement {
1861 div()
1862 .id(("row-header", row_ix))
1863 .w_3()
1864 .h_full()
1865 .border_r_1()
1866 .border_color(cx.theme().table_row_border)
1867 .bg(cx.theme().tokens.table_head)
1868 .flex_shrink_0()
1869 .table_cell_size(self.options.size)
1870 .when(!is_head, |this| {
1871 this.when(self.row_selectable, |this| {
1872 this.on_click(cx.listener(move |table, e: &ClickEvent, _window, cx| {
1873 cx.stop_propagation();
1874 if table.selects_row_on_click(e, cx) {
1875 table.set_selected_row(row_ix, cx);
1876 }
1877 }))
1878 })
1879 })
1880 }
1881
1882 fn render_sort_icon(
1883 &self,
1884 col_ix: usize,
1885 col_group: &ColGroup,
1886 _: &mut Window,
1887 cx: &mut Context<Self>,
1888 ) -> Option<impl IntoElement> {
1889 if !self.sortable {
1890 return None;
1891 }
1892
1893 let Some(sort) = col_group.column.sort else {
1894 return None;
1895 };
1896
1897 let (icon, is_on) = match sort {
1898 ColumnSort::Ascending => (IconName::SortAscending, true),
1899 ColumnSort::Descending => (IconName::SortDescending, true),
1900 ColumnSort::Default => (IconName::ChevronsUpDown, false),
1901 };
1902
1903 Some(
1904 div()
1905 .id(("icon-sort", col_ix))
1906 .test_support()
1907 .role(gpui::Role::Button)
1908 .aria_label(t!("Table.SortBy", column = col_group.column.name).to_string())
1909 .p(px(2.))
1910 .rounded(cx.theme().radius / 2.)
1911 .map(|this| match is_on {
1912 true => this,
1913 false => this.opacity(0.5),
1914 })
1915 .hover(|this| this.bg(cx.theme().tokens.secondary).opacity(7.))
1916 .active(|this| this.bg(cx.theme().tokens.secondary_active).opacity(1.))
1917 .on_click(
1918 cx.listener(move |table, _, window, cx| table.perform_sort(col_ix, window, cx)),
1919 )
1920 .child(
1921 Icon::new(icon)
1922 .size_3()
1923 .text_color(cx.theme().secondary_foreground),
1924 ),
1925 )
1926 }
1927
1928 fn render_th(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) -> Div {
1933 let entity_id = cx.entity_id();
1934 let col_group = self.col_groups.get(col_ix).expect("BUG: invalid col index");
1935
1936 let movable = self.col_movable && col_group.column.movable;
1937 let paddings = col_group.column.paddings;
1938 let name = col_group.column.name.clone();
1939
1940 h_flex()
1941 .h_full()
1942 .child(
1943 self.render_cell(None, col_ix, window, cx)
1944 .when(
1949 self.options.header_row_height.is_some() && paddings.is_none(),
1950 |this| this.py_0(),
1951 )
1952 .id(("col-header", col_ix))
1953 .role(gpui::Role::ColumnHeader)
1954 .aria_label(name.clone())
1955 .aria_column_index(col_ix)
1956 .test_support()
1957 .on_click(cx.listener(move |this, _, window, cx| {
1958 this.on_col_head_click(col_ix, window, cx);
1959 }))
1960 .child(
1961 h_flex()
1962 .size_full()
1963 .justify_between()
1964 .items_center()
1965 .child(self.delegate.render_th(col_ix, window, cx))
1966 .when_some(paddings, |this, paddings| {
1967 let offset_pr =
1969 self.options.size.table_cell_padding().right - paddings.right;
1970 this.pr(offset_pr.max(px(0.)))
1971 })
1972 .children(self.render_sort_icon(col_ix, &col_group, window, cx)),
1973 )
1974 .when(movable, |this| {
1975 this.on_drag(
1976 DragColumn {
1977 entity_id,
1978 col_ix,
1979 name,
1980 width: col_group.width,
1981 },
1982 |drag, _, _, cx| {
1983 cx.stop_propagation();
1984 cx.new(|_| drag.clone())
1985 },
1986 )
1987 })
1988 .map(|this| {
1989 let last_gap = col_ix + 1 == self.col_groups.len();
1994 match self.col_drag_gap {
1995 Some(gap)
1996 if cx.has_active_drag()
1997 && (gap == col_ix || (last_gap && gap == col_ix + 1)) =>
1998 {
1999 let right_side = gap == col_ix + 1;
2000 this.relative().child(
2001 div()
2002 .absolute()
2003 .top_0()
2004 .bottom_0()
2005 .w(px(2.))
2006 .map(|d| if right_side { d.right_0() } else { d.left_0() })
2007 .bg(cx.theme().drag_border),
2008 )
2009 }
2010 _ => this,
2011 }
2012 }),
2013 )
2014 .child(self.render_resize_handle(col_ix, window, cx))
2016 .child(self.render_leading_resize_handle(col_ix, window, cx))
2018 .on_prepaint({
2020 let view = cx.entity();
2021 move |bounds, _, cx| view.update(cx, |r, _| r.col_groups[col_ix].bounds = bounds)
2022 })
2023 }
2024
2025 fn calculate_visible_leaf_col_range(
2035 &self,
2036 scrollable_cols: Range<usize>,
2037 ) -> (Range<usize>, Pixels) {
2038 let (left_columns_count, total_cols) = (scrollable_cols.start, scrollable_cols.end);
2039
2040 if self.bounds.size.width == px(0.) {
2041 return (scrollable_cols, px(0.));
2042 }
2043
2044 let fixed_width =
2045 self.fixed_head_cols_bounds.size.width + self.fixed_right_head_cols_bounds.size.width;
2046 let available_width = (self.bounds.size.width - fixed_width).max(px(0.));
2047 let scroll_x = (-self.horizontal_scroll_handle.offset().x).max(px(0.));
2050
2051 let mut range_start = left_columns_count;
2055 let mut left_spacer = px(0.);
2056 let mut cumulative = px(0.);
2057 for i in left_columns_count..total_cols {
2058 let right_edge = cumulative + self.col_groups[i].width;
2059 if right_edge > scroll_x {
2060 range_start = i;
2061 left_spacer = cumulative;
2062 break;
2063 }
2064 cumulative = right_edge;
2065 }
2066
2067 let right_bound = scroll_x + available_width + px(200.);
2071 let mut range_end = total_cols;
2072 let mut cumulative = left_spacer; for i in range_start..total_cols {
2074 cumulative += self.col_groups[i].width;
2075 if cumulative > right_bound {
2076 range_end = (i + 1).min(total_cols);
2077 break;
2078 }
2079 }
2080
2081 (range_start..range_end, left_spacer)
2082 }
2083
2084 fn render_table_header(
2085 &mut self,
2086 scrollable_cols: Range<usize>,
2087 window: &mut Window,
2088 cx: &mut Context<Self>,
2089 ) -> impl IntoElement {
2090 let horizontal_scroll_handle = self.horizontal_scroll_handle.clone();
2091
2092 let total_cols = self.col_groups.len();
2106 let left_columns_count = scrollable_cols.start;
2107 let right_columns_start = scrollable_cols.end;
2108 let (visible_col_range, left_spacer) =
2109 self.calculate_visible_leaf_col_range(scrollable_cols.clone());
2110
2111 let layout_len = self.header_layout.len();
2112 let header_row_height = self.header_row_height();
2113
2114 if left_columns_count == 0 {
2116 self.fixed_head_cols_bounds = Bounds::default();
2117 }
2118 if right_columns_start == total_cols {
2119 self.fixed_right_head_cols_bounds = Bounds::default();
2120 }
2121
2122 let mut header = self.delegate_mut().render_header(window, cx);
2123 let style = header.style().clone();
2124 let layout = self.header_layout.clone();
2125
2126 header
2127 .role(gpui::Role::Row)
2130 .aria_row_index(0)
2131 .h_flex()
2132 .w_full()
2133 .flex_shrink_0()
2134 .bg(cx.theme().tokens.table_head)
2135 .text_color(cx.theme().table_head_foreground)
2136 .refine_style(&style)
2137 .on_drag_move(cx.listener(|table, e: &DragMoveEvent<DragColumn>, _, cx| {
2138 let drag = e.drag(cx);
2139 let (drag_entity_id, drag_col_ix) = (drag.entity_id, drag.col_ix);
2140
2141 let gap =
2142 if drag_entity_id == cx.entity_id() && e.bounds.contains(&e.event.position) {
2143 table.drag_gap_at(e.event.position.x, drag_col_ix)
2144 } else {
2145 None
2146 };
2147
2148 if table.col_drag_gap != gap {
2149 table.col_drag_gap = gap;
2150 cx.notify();
2151 }
2152 }))
2153 .on_drop(cx.listener(|table, drag: &DragColumn, window, cx| {
2154 if drag.entity_id != cx.entity_id() {
2155 return;
2156 }
2157
2158 let Some(gap) = table.col_drag_gap.take() else {
2160 return;
2161 };
2162 let to_ix = if drag.col_ix < gap { gap - 1 } else { gap };
2163 table.move_column(drag.col_ix, to_ix, window, cx);
2164 }))
2165 .when(self.cell_selectable && self.row_header, |this| {
2166 this.child(self.render_row_header_cell(0, true, cx))
2167 })
2168 .when(left_columns_count > 0, |this| {
2169 this.child(self.render_fixed_head_cols(
2170 0..left_columns_count,
2171 ColumnFixed::Left,
2172 window,
2173 cx,
2174 ))
2175 })
2176 .child(
2177 h_flex()
2179 .id("table-head")
2180 .size_full()
2181 .overflow_scroll()
2182 .relative()
2183 .track_scroll(&horizontal_scroll_handle)
2184 .bg(cx.theme().tokens.table_head)
2185 .child(v_flex().min_w_full().flex_shrink_0().children(
2186 layout.iter().enumerate().map(|(row_ix, row_cells)| {
2187 let is_leaf_row = row_ix + 1 == layout_len;
2188 h_flex()
2189 .min_w_full()
2190 .h(header_row_height)
2191 .border_b_1()
2192 .border_color(cx.theme().border)
2193 .map(|this| {
2194 if is_leaf_row {
2195 this.when(left_spacer > px(0.), |r| {
2200 r.child(div().w(left_spacer).h_full().flex_shrink_0())
2201 })
2202 .children(row_cells.iter().filter_map(|cell| {
2203 if cell.is_leaf {
2204 let ix = cell.leaf_col_ix?;
2205 if !visible_col_range.contains(&ix) {
2206 return None;
2207 }
2208 Some(
2209 self.render_th(ix, window, cx)
2210 .into_any_element(),
2211 )
2212 } else {
2213 None
2214 }
2215 }))
2216 .when(visible_col_range.end < right_columns_start, |r| {
2217 let right_spacer: Pixels = self.col_groups
2218 [visible_col_range.end..right_columns_start]
2219 .iter()
2220 .map(|g| g.width)
2221 .sum();
2222 r.child(div().w(right_spacer).h_full().flex_shrink_0())
2223 })
2224 .child(self.delegate.render_last_empty_col(window, cx))
2225 } else {
2226 this.children(row_cells.iter().filter_map(|cell| {
2229 if scrollable_cols.contains(&cell.start_leaf_col_ix) {
2230 if cell.is_leaf {
2231 if let Some(ix) = cell.leaf_col_ix {
2232 return Some(
2233 self.render_th(ix, window, cx)
2234 .into_any_element(),
2235 );
2236 }
2237 } else {
2238 return Some(
2239 self.delegate_mut()
2240 .render_group_th(
2241 &cell.label,
2242 cell.col_span,
2243 cell.width,
2244 window,
2245 cx,
2246 )
2247 .into_any_element(),
2248 );
2249 }
2250 }
2251 None
2252 }))
2253 .child(self.delegate.render_last_empty_col(window, cx))
2254 }
2255 })
2256 }),
2257 )),
2258 )
2259 .when(right_columns_start < total_cols, |this| {
2260 this.child(self.render_fixed_head_cols(
2261 right_columns_start..total_cols,
2262 ColumnFixed::Right,
2263 window,
2264 cx,
2265 ))
2266 })
2267 }
2268
2269 fn render_fixed_head_cols(
2272 &mut self,
2273 cols: Range<usize>,
2274 side: ColumnFixed,
2275 window: &mut Window,
2276 cx: &mut Context<Self>,
2277 ) -> impl IntoElement {
2278 let view = cx.entity();
2279 let header_row_height = self.header_row_height();
2280 let layout = self.header_layout.clone();
2281
2282 h_flex()
2283 .relative()
2284 .h_full()
2285 .flex_shrink_0()
2286 .bg(cx.theme().tokens.table_head)
2287 .child(
2288 v_flex()
2289 .min_w_full()
2290 .flex_shrink_0()
2291 .children(layout.iter().map(|row_cells| {
2292 h_flex()
2293 .min_w_full()
2294 .h(header_row_height)
2295 .border_b_1()
2296 .border_color(cx.theme().border)
2297 .children(row_cells.iter().filter_map(|cell| {
2298 if !cols.contains(&cell.start_leaf_col_ix) {
2299 return None;
2300 }
2301
2302 if cell.is_leaf {
2303 let ix = cell.leaf_col_ix?;
2304 Some(self.render_th(ix, window, cx).into_any_element())
2305 } else {
2306 Some(
2307 self.delegate_mut()
2308 .render_group_th(
2309 &cell.label,
2310 cell.col_span,
2311 cell.width,
2312 window,
2313 cx,
2314 )
2315 .into_any_element(),
2316 )
2317 }
2318 }))
2319 })),
2320 )
2321 .children(self.render_fixed_cols_border(side, cx))
2322 .on_prepaint(move |bounds, _, cx| {
2323 view.update(cx, |table, _| match side {
2324 ColumnFixed::Left => table.fixed_head_cols_bounds = bounds,
2325 ColumnFixed::Right => table.fixed_right_head_cols_bounds = bounds,
2326 })
2327 })
2328 }
2329
2330 #[allow(clippy::too_many_arguments)]
2331 fn render_table_row(
2332 &mut self,
2333 row_ix: usize,
2334 rows_count: usize,
2335 scrollable_cols: Range<usize>,
2336 col_sizes: Rc<Vec<gpui::Size<Pixels>>>,
2337 columns_count: usize,
2338 is_filled: bool,
2339 window: &mut Window,
2340 cx: &mut Context<Self>,
2341 ) -> gpui::AnyElement {
2342 let is_stripe_row = self.options.stripe && row_ix % 2 != 0;
2343 let is_selected = self.selected_row() == Some(row_ix);
2346 let view = cx.entity();
2347 let row_height = self.options.size.table_row_height();
2348
2349 if row_ix < rows_count {
2350 let is_last_row = row_ix + 1 == rows_count;
2351 let need_render_border = is_selected || !is_last_row || !is_filled;
2352
2353 let mut tr = self.delegate.render_tr(row_ix, window, cx);
2354 let style = tr.style().clone();
2355 let label = if window.is_a11y_active() || cfg!(feature = "test-support") {
2357 self.delegate.row_label(row_ix, cx)
2358 } else {
2359 None
2360 };
2361
2362 tr.test_support()
2363 .role(gpui::Role::Row)
2364 .aria_row_index(row_ix + 1)
2366 .when_some(label, |this, label| this.aria_label(label))
2367 .aria_selected(is_selected)
2368 .when(
2371 is_selected && self.focus_handle.is_focused(window),
2372 |this| this.aria_active_descendant(),
2373 )
2374 .h_flex()
2375 .w_full()
2376 .h(row_height)
2377 .when(need_render_border, |this| {
2378 this.border_b_1().border_color(cx.theme().table_row_border)
2379 })
2380 .when(is_stripe_row, |this| this.bg(cx.theme().tokens.table_even))
2381 .refine_style(&style)
2382 .hover(|this| {
2383 if is_selected || self.right_clicked_row == Some(row_ix) {
2384 this
2385 } else {
2386 this.bg(cx.theme().tokens.table_hover)
2387 }
2388 })
2389 .when(self.cell_selectable && self.row_header, |this| {
2390 this.child(self.render_row_header_cell(row_ix, false, cx))
2391 })
2392 .when(scrollable_cols.start > 0, |this| {
2393 this.child(self.render_fixed_cells(
2394 row_ix,
2395 0..scrollable_cols.start,
2396 ColumnFixed::Left,
2397 window,
2398 cx,
2399 ))
2400 })
2401 .child(
2402 h_flex()
2403 .flex_1()
2404 .h_full()
2405 .overflow_hidden()
2406 .relative()
2407 .child(
2408 crate::virtual_list::virtual_list(
2409 view,
2410 row_ix,
2411 Axis::Horizontal,
2412 col_sizes,
2413 {
2414 let scrollable_cols = scrollable_cols.clone();
2415 move |table, visible_range: Range<usize>, window, cx| {
2416 table.update_visible_range_if_need(
2417 visible_range.clone(),
2418 scrollable_cols.len(),
2419 Axis::Horizontal,
2420 window,
2421 cx,
2422 );
2423
2424 let mut items = Vec::with_capacity(
2425 visible_range.end - visible_range.start,
2426 );
2427
2428 visible_range.for_each(|col_ix| {
2429 let col_ix = col_ix + scrollable_cols.start;
2430 let is_cell_selected =
2431 table.selected_cell() == Some((row_ix, col_ix));
2432 let is_cell_right_clicked =
2433 table.right_clicked_cell == Some((row_ix, col_ix));
2434
2435 let el = table
2436 .render_col_wrap(Some(row_ix), col_ix, window, cx)
2437 .child(
2438 table
2439 .a11y_cell(
2440 table
2441 .render_cell(
2442 Some(row_ix),
2443 col_ix,
2444 window,
2445 cx,
2446 )
2447 .id(format!(
2448 "table-cell-{}:{}",
2449 row_ix, col_ix
2450 ))
2451 .test_support(),
2452 row_ix,
2453 col_ix,
2454 window,
2455 cx,
2456 )
2457 .relative()
2458 .child(table.measure_render_td(
2459 row_ix, col_ix, window, cx,
2460 ))
2461 .when(is_cell_selected, |this| {
2462 this.child(
2463 div()
2464 .absolute()
2465 .inset_0()
2466 .bg(cx
2467 .theme()
2468 .tokens
2469 .table_active)
2470 .border_1()
2471 .border_color(
2472 cx.theme()
2473 .table_active_border,
2474 ),
2475 )
2476 })
2477 .when(
2478 is_cell_right_clicked
2479 && !is_cell_selected,
2480 |this| {
2481 this.child(
2482 div()
2483 .absolute()
2484 .inset_0()
2485 .border_1()
2486 .border_color(
2487 cx.theme()
2488 .table_active_border
2489 .opacity(0.5),
2490 ),
2491 )
2492 },
2493 )
2494 .when(table.cell_selectable, |this| {
2495 this.on_click(cx.listener(
2496 move |table, e, window, cx| {
2497 cx.stop_propagation();
2498 table.on_cell_click(
2499 e, row_ix, col_ix, window,
2500 cx,
2501 );
2502 },
2503 ))
2504 .on_mouse_down(
2505 MouseButton::Right,
2506 cx.listener(
2507 move |table, e, window, cx| {
2508 table.on_cell_right_click(
2509 e, row_ix, col_ix,
2510 window, cx,
2511 );
2512 },
2513 ),
2514 )
2515 }),
2516 );
2517
2518 items.push(el);
2519 });
2520
2521 items
2522 }
2523 },
2524 )
2525 .with_scroll_handle(&self.horizontal_scroll_handle),
2526 )
2527 .child(self.delegate.render_last_empty_col(window, cx)),
2528 )
2529 .when(scrollable_cols.end < self.col_groups.len(), |this| {
2530 this.child(self.render_fixed_cells(
2531 row_ix,
2532 scrollable_cols.end..self.col_groups.len(),
2533 ColumnFixed::Right,
2534 window,
2535 cx,
2536 ))
2537 })
2538 .when(is_selected, |this| {
2540 let bg = if cx.theme().list.active_highlight {
2541 cx.theme().tokens.table_active
2542 } else {
2543 cx.theme().tokens.accent
2544 };
2545 this.bg(bg)
2546 })
2547 .when(self.right_clicked_row == Some(row_ix), |this| {
2549 this.border_color(gpui::transparent_white()).child(
2550 div()
2551 .top(if row_ix == 0 { px(0.) } else { px(-1.) })
2552 .left(px(0.))
2553 .right(px(0.))
2554 .bottom(px(-1.))
2555 .absolute()
2556 .border_1()
2557 .border_color(cx.theme().selection),
2558 )
2559 })
2560 .on_mouse_down(
2561 MouseButton::Right,
2562 cx.listener(move |this, e, window, cx| {
2563 this.on_row_right_click(e, Some(row_ix), window, cx);
2564 }),
2565 )
2566 .on_click(cx.listener(move |this, e, window, cx| {
2567 this.on_row_left_click(e, row_ix, window, cx);
2568 }))
2569 .into_any_element()
2570 } else {
2571 let cols_width: Pixels = self
2572 .col_groups
2573 .iter()
2574 .take(columns_count)
2575 .map(|col_group| col_group.width)
2576 .sum();
2577
2578 self.delegate
2580 .render_tr(row_ix, window, cx)
2581 .h_flex()
2582 .w_full()
2583 .h(row_height)
2584 .border_b_1()
2585 .border_color(cx.theme().table_row_border)
2586 .when(is_stripe_row, |this| this.bg(cx.theme().tokens.table_even))
2587 .when(self.cell_selectable && self.row_header, |this| {
2588 this.child(
2590 div()
2591 .w(px(40.))
2592 .h_full()
2593 .flex_shrink_0()
2594 .table_cell_size(self.options.size),
2595 )
2596 })
2597 .child(div().flex_shrink_0().h_full().w(cols_width))
2601 .child(self.delegate.render_last_empty_col(window, cx))
2602 .into_any_element()
2603 }
2604 }
2605
2606 fn render_fixed_cells(
2608 &mut self,
2609 row_ix: usize,
2610 cols: Range<usize>,
2611 side: ColumnFixed,
2612 window: &mut Window,
2613 cx: &mut Context<Self>,
2614 ) -> impl IntoElement {
2615 let items: Vec<_> = cols
2616 .map(|col_ix| {
2617 let is_cell_selected = self.selected_cell() == Some((row_ix, col_ix));
2618 let is_cell_right_clicked = self.right_clicked_cell == Some((row_ix, col_ix));
2619
2620 self.render_col_wrap(Some(row_ix), col_ix, window, cx)
2621 .child(
2622 self.a11y_cell(
2623 self.render_cell(Some(row_ix), col_ix, window, cx)
2624 .id(format!("table-cell:{}:{}", row_ix, col_ix))
2625 .test_support(),
2626 row_ix,
2627 col_ix,
2628 window,
2629 cx,
2630 )
2631 .relative()
2632 .child(self.measure_render_td(row_ix, col_ix, window, cx))
2633 .when(is_cell_selected, |this| {
2634 this.child(
2635 div()
2636 .absolute()
2637 .inset_0()
2638 .bg(cx.theme().tokens.table_active)
2639 .border_1()
2640 .border_color(cx.theme().table_active_border),
2641 )
2642 })
2643 .when(is_cell_right_clicked && !is_cell_selected, |this| {
2644 this.child(
2645 div()
2646 .absolute()
2647 .inset_0()
2648 .border_1()
2649 .border_color(cx.theme().table_active_border.opacity(0.5)),
2650 )
2651 })
2652 .when(self.cell_selectable, |this| {
2653 this.on_click(cx.listener(move |table, e, window, cx| {
2654 table.on_cell_click(e, row_ix, col_ix, window, cx);
2655 }))
2656 .on_mouse_down(
2657 MouseButton::Right,
2658 cx.listener(move |table, e, window, cx| {
2659 table.on_cell_right_click(e, row_ix, col_ix, window, cx);
2660 }),
2661 )
2662 }),
2663 )
2664 })
2665 .collect();
2666
2667 h_flex()
2668 .relative()
2669 .h_full()
2670 .flex_shrink_0()
2671 .children(items)
2672 .children(self.render_fixed_cols_border(side, cx))
2673 }
2674
2675 fn calculate_extra_rows_needed(
2677 &self,
2678 total_height: Pixels,
2679 actual_height: Pixels,
2680 row_height: Pixels,
2681 ) -> usize {
2682 let mut extra_rows_needed = 0;
2683
2684 let remaining_height = total_height - actual_height;
2685 if remaining_height > px(0.) {
2686 extra_rows_needed = (remaining_height / row_height).floor() as usize;
2687 }
2688
2689 extra_rows_needed
2690 }
2691
2692 #[inline]
2693 fn measure_render_td(
2694 &mut self,
2695 row_ix: usize,
2696 col_ix: usize,
2697 window: &mut Window,
2698 cx: &mut Context<Self>,
2699 ) -> impl IntoElement {
2700 if !crate::measure_enable() {
2701 return self
2702 .delegate
2703 .render_td(row_ix, col_ix, window, cx)
2704 .into_any_element();
2705 }
2706
2707 let start = std::time::Instant::now();
2708 let el = self.delegate.render_td(row_ix, col_ix, window, cx);
2709 self._measure.push(start.elapsed());
2710 el.into_any_element()
2711 }
2712
2713 fn measure(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
2714 if !crate::measure_enable() {
2715 return;
2716 }
2717
2718 if self._measure.len() > 0 {
2720 let total = self
2721 ._measure
2722 .iter()
2723 .fold(Duration::default(), |acc, d| acc + *d);
2724 let avg = total / self._measure.len() as u32;
2725 eprintln!(
2726 "last render {} cells total: {:?}, avg: {:?}",
2727 self._measure.len(),
2728 total,
2729 avg,
2730 );
2731 }
2732 self._measure.clear();
2733 }
2734
2735 fn render_vertical_scrollbar(
2736 &mut self,
2737 _: &mut Window,
2738 _: &mut Context<Self>,
2739 ) -> Option<impl IntoElement> {
2740 Some(
2741 div()
2742 .absolute()
2743 .top(self.header_band_height())
2744 .right_0()
2745 .bottom_0()
2746 .w(Scrollbar::width())
2747 .child(
2748 Scrollbar::vertical(&self.vertical_scroll_handle)
2749 .viewport_from_layout()
2750 .when_some(self.options.scrollbar_mode, |this, mode| this.mode(mode))
2751 .max_fps(60),
2752 ),
2753 )
2754 }
2755
2756 fn render_horizontal_scrollbar(
2757 &mut self,
2758 _: &mut Window,
2759 _: &mut Context<Self>,
2760 ) -> impl IntoElement {
2761 div()
2762 .absolute()
2763 .left(self.fixed_head_cols_bounds.size.width)
2764 .right(self.fixed_right_head_cols_bounds.size.width)
2765 .bottom_0()
2766 .h(Scrollbar::width())
2767 .child(
2768 Scrollbar::horizontal(&self.horizontal_scroll_handle)
2769 .viewport_from_layout()
2770 .when_some(self.options.scrollbar_mode, |this, mode| this.mode(mode)),
2771 )
2772 }
2773}
2774
2775impl<D> Focusable for TableState<D>
2776where
2777 D: TableDelegate,
2778{
2779 fn focus_handle(&self, _cx: &gpui::App) -> FocusHandle {
2780 self.focus_handle.clone()
2781 }
2782}
2783impl<D> EventEmitter<TableEvent> for TableState<D> where D: TableDelegate {}
2784
2785impl<D> Render for TableState<D>
2786where
2787 D: TableDelegate,
2788{
2789 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2790 self.measure(window, cx);
2791
2792 let columns_count = self.delegate.columns_count(cx);
2793 let scrollable_cols = self.scrollable_cols();
2794 let rows_count = self.delegate.rows_count(cx);
2795 let loading = self.delegate.loading(cx);
2796
2797 let row_height = self.options.size.table_row_height();
2798 let total_height = self
2799 .vertical_scroll_handle
2800 .0
2801 .borrow()
2802 .base_handle
2803 .bounds()
2804 .size
2805 .height;
2806 let actual_height = row_height * rows_count as f32;
2807 let extra_rows_count =
2808 self.calculate_extra_rows_needed(total_height, actual_height, row_height);
2809 let render_rows_count = if self.options.stripe {
2810 rows_count + extra_rows_count
2811 } else {
2812 rows_count
2813 };
2814 let has_right_click = self.right_clicked_row.is_some() || self.right_clicked_cell.is_some();
2815 let is_filled = total_height > Pixels::ZERO && total_height <= actual_height;
2816
2817 let loading_view = if loading {
2818 Some(
2819 self.delegate
2820 .render_loading(self.options.size, window, cx)
2821 .into_any_element(),
2822 )
2823 } else {
2824 None
2825 };
2826
2827 let empty_view = if rows_count == 0 {
2828 self.update_visible_range_if_need(0..0, 0, Axis::Vertical, window, cx);
2830 Some(
2831 div()
2832 .size_full()
2833 .child(self.delegate.render_empty(window, cx))
2834 .into_any_element(),
2835 )
2836 } else {
2837 None
2838 };
2839
2840 let inner_table = v_flex()
2841 .id("table-inner")
2842 .test_support()
2843 .size_full()
2844 .overflow_hidden()
2845 .child(self.render_table_header(scrollable_cols.clone(), window, cx))
2846 .context_menu({
2847 let view = cx.entity();
2848 move |this, window: &mut Window, cx: &mut Context<PopupMenu>| {
2849 if let Some(row_ix) = view.read(cx).right_clicked_row {
2850 view.update(cx, |menu, cx| {
2851 menu.delegate_mut().context_menu(row_ix, this, window, cx)
2852 })
2853 } else {
2854 this
2855 }
2856 }
2857 })
2858 .map(|this| {
2859 if rows_count == 0 {
2860 this.children(empty_view)
2861 } else {
2862 this.child(
2863 h_flex().id("table-body").flex_grow_1().size_full().child(
2864 uniform_list(
2865 "table-uniform-list",
2866 render_rows_count,
2867 cx.processor(
2868 move |table, visible_range: Range<usize>, window, cx| {
2869 let col_sizes: Rc<Vec<gpui::Size<Pixels>>> = Rc::new(
2873 table
2874 .col_groups
2875 .get(scrollable_cols.clone())
2876 .unwrap_or_default()
2877 .iter()
2878 .map(|col| gpui::Size {
2879 width: col.width,
2880 height: px(0.),
2881 })
2882 .collect(),
2883 );
2884
2885 table.load_more_if_need(
2886 rows_count,
2887 visible_range.end,
2888 window,
2889 cx,
2890 );
2891 table.update_visible_range_if_need(
2892 visible_range.clone(),
2893 rows_count,
2894 Axis::Vertical,
2895 window,
2896 cx,
2897 );
2898
2899 if visible_range.start >= rows_count {
2900 table.scroll_to_row(rows_count.saturating_sub(1), cx);
2901 }
2902
2903 let mut items = Vec::with_capacity(
2904 visible_range.end.saturating_sub(visible_range.start),
2905 );
2906
2907 visible_range.for_each(|row_ix| {
2909 items.push(table.render_table_row(
2911 row_ix,
2912 rows_count,
2913 scrollable_cols.clone(),
2914 col_sizes.clone(),
2915 columns_count,
2916 is_filled,
2917 window,
2918 cx,
2919 ));
2920 });
2921
2922 items
2923 },
2924 ),
2925 )
2926 .flex_grow_1()
2927 .size_full()
2928 .with_sizing_behavior(ListSizingBehavior::Auto)
2929 .track_scroll(&self.vertical_scroll_handle)
2930 .map(|rows| {
2931 gpui_base::ScrollBounce::new(
2932 "table-scroll-bounce",
2933 &self.vertical_scroll_handle,
2934 rows,
2935 )
2936 .when_some(self.options.scroll_bounce, |bounce, on| {
2937 bounce.enabled(on)
2938 })
2939 })
2940 .into_any_element(),
2941 ),
2942 )
2943 }
2944 });
2945
2946 div()
2947 .size_full()
2948 .children(loading_view)
2949 .when(!loading, |this| {
2950 this.child(inner_table)
2951 .child(ScrollableMask::new(
2952 Axis::Horizontal,
2953 &self.horizontal_scroll_handle,
2954 ))
2955 .when(rows_count > 0, |this| {
2960 this.child(ScrollableMask::new(
2961 Axis::Vertical,
2962 &self.vertical_scroll_handle.0.borrow().base_handle,
2963 ))
2964 })
2965 .when(has_right_click, |this| {
2966 this.on_mouse_down_out(cx.listener(|this, e, window, cx| {
2967 this.on_row_right_click(e, None, window, cx);
2968 cx.notify();
2969 }))
2970 })
2971 })
2972 .on_prepaint({
2973 let state = cx.entity();
2974 move |bounds, _, cx| state.update(cx, |state, _| state.bounds = bounds)
2975 })
2976 .when(!window.is_inspector_picking(cx), |this| {
2977 this.child(
2978 div()
2979 .absolute()
2980 .top_0()
2981 .size_full()
2982 .when(self.options.scrollbar_visible.bottom, |this| {
2983 this.child(self.render_horizontal_scrollbar(window, cx))
2984 })
2985 .when(
2986 self.options.scrollbar_visible.right && rows_count > 0,
2987 |this| this.children(self.render_vertical_scrollbar(window, cx)),
2988 ),
2989 )
2990 })
2991 }
2992}
2993
2994#[cfg(test)]
2995mod tests {
2996 use gpui::{AnyView, App, Entity, StyleRefinement, TestAppContext};
2997
2998 use super::*;
2999
3000 struct WidthsDelegate;
3001
3002 struct BounceDelegate;
3003
3004 impl TableDelegate for BounceDelegate {
3005 fn columns_count(&self, _: &App) -> usize {
3006 1
3007 }
3008 fn rows_count(&self, _: &App) -> usize {
3009 40
3010 }
3011 fn column(&self, _: usize, _: &App) -> Column {
3012 Column::new("value", "Value")
3013 }
3014 fn render_td(
3015 &mut self,
3016 row: usize,
3017 _: usize,
3018 _: &mut Window,
3019 _: &mut Context<TableState<Self>>,
3020 ) -> impl IntoElement {
3021 div().child(row.to_string())
3022 }
3023 }
3024
3025 struct BounceTable(Entity<TableState<BounceDelegate>>);
3026
3027 impl Render for BounceTable {
3028 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3029 div()
3030 .w(px(240.))
3031 .h(px(200.))
3032 .child(DataTable::new(&self.0).scroll_bounce(true))
3033 }
3034 }
3035
3036 #[gpui::test]
3037 fn scroll_bounce_table_keeps_headers_fixed_and_accepts_new_wheel_input(
3038 cx: &mut TestAppContext,
3039 ) {
3040 cx.update(crate::init);
3041 let (view, cx) = cx.add_window_view(|window, cx| {
3042 BounceTable(cx.new(|cx| TableState::new(BounceDelegate, window, cx)))
3043 });
3044 cx.update(|window, cx| window.draw(cx).clear(cx));
3045 let state = view.read_with(cx, |view, _| view.0.clone());
3046 let header = state.read_with(cx, |state, _| state.col_groups[0].bounds);
3047 let wheel = |cx: &mut gpui::VisualTestContext, dy| {
3048 cx.simulate_event(gpui::ScrollEvent {
3049 position: gpui::point(px(100.), px(100.)),
3050 delta: gpui::ScrollDelta::Lines(gpui::point(0., dy)),
3051 ..Default::default()
3052 });
3053 };
3054 for (dy, phase) in [
3055 (-10000., gpui::TouchPhase::Started),
3056 (0., gpui::TouchPhase::Ended),
3057 ] {
3058 cx.simulate_event(gpui::ScrollEvent {
3059 position: gpui::point(px(100.), px(100.)),
3060 delta: gpui::ScrollDelta::Pixels(gpui::point(px(0.), px(dy))),
3061 touch_phase: phase,
3062 ..Default::default()
3063 });
3064 }
3065 cx.update(|window, cx| window.draw(cx).clear(cx));
3066 let end = state.read_with(cx, |state, _| {
3067 state
3068 .vertical_scroll_handle
3069 .0
3070 .borrow()
3071 .base_handle
3072 .offset()
3073 .y
3074 });
3075 assert!(end < px(0.));
3076 cx.executor().advance_clock(Duration::from_millis(200));
3077 cx.update(|window, cx| window.draw(cx).clear(cx));
3078 assert_eq!(
3079 state.read_with(cx, |state, _| state.col_groups[0].bounds),
3080 header
3081 );
3082 wheel(cx, 2.);
3083 assert!(
3084 state.read_with(cx, |state, _| state
3085 .vertical_scroll_handle
3086 .0
3087 .borrow()
3088 .base_handle
3089 .offset()
3090 .y)
3091 > end
3092 );
3093 }
3094
3095 struct ThreeRowsDelegate;
3096
3097 impl TableDelegate for ThreeRowsDelegate {
3098 fn columns_count(&self, _: &App) -> usize {
3099 1
3100 }
3101 fn rows_count(&self, _: &App) -> usize {
3102 3
3103 }
3104 fn column(&self, _: usize, _: &App) -> Column {
3105 Column::new("value", "Value")
3106 }
3107 fn render_td(
3108 &mut self,
3109 row: usize,
3110 _: usize,
3111 _: &mut Window,
3112 _: &mut Context<TableState<Self>>,
3113 ) -> impl IntoElement {
3114 div().child(row.to_string())
3115 }
3116 }
3117
3118 struct StripedPanel {
3120 table: Entity<TableState<ThreeRowsDelegate>>,
3121 renders: usize,
3122 }
3123
3124 impl Render for StripedPanel {
3125 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3126 self.renders += 1;
3127 div()
3128 .size_full()
3129 .child(DataTable::new(&self.table).stripe(true))
3130 }
3131 }
3132
3133 struct CachedPanel(Entity<StripedPanel>);
3135
3136 impl Render for CachedPanel {
3137 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3138 div()
3139 .w(px(240.))
3140 .h(px(400.))
3141 .child(AnyView::from(self.0.clone()).cached(StyleRefinement::default().size_full()))
3142 }
3143 }
3144
3145 #[gpui::test]
3149 fn striped_table_with_few_rows_lets_a_cached_view_be_reused(cx: &mut TestAppContext) {
3150 cx.update(crate::init);
3151 let (view, cx) = cx.add_window_view(|window, cx| {
3152 let table = cx.new(|cx| TableState::new(ThreeRowsDelegate, window, cx));
3153 CachedPanel(cx.new(|_| StripedPanel { table, renders: 0 }))
3154 });
3155 let panel = view.read_with(cx, |view, _| view.0.clone());
3156 let table = panel.read_with(cx, |panel, _| panel.table.clone());
3157 let draw = |cx: &mut gpui::VisualTestContext| {
3158 cx.update(|window, cx| window.draw(cx).clear(cx));
3159 };
3160 draw(cx);
3161 table.update(cx, |_, cx| cx.notify());
3163 draw(cx);
3164 let renders = panel.read_with(cx, |panel, _| panel.renders);
3165 draw(cx);
3166 draw(cx);
3167 assert_eq!(panel.read_with(cx, |panel, _| panel.renders), renders);
3168 }
3169
3170 impl TableDelegate for WidthsDelegate {
3171 fn columns_count(&self, _: &App) -> usize {
3172 6
3173 }
3174
3175 fn rows_count(&self, _: &App) -> usize {
3176 0
3177 }
3178
3179 fn column(&self, col_ix: usize, _: &App) -> Column {
3180 match col_ix {
3181 0 => Column::new("narrow", "Narrow")
3182 .min_width(px(80.))
3183 .width(px(40.)),
3184 1 => Column::new("wide", "Wide")
3185 .max_width(px(120.))
3186 .width(px(300.)),
3187 2 => Column::new("tiny", "Tiny").width(px(10.)),
3189 3 => Column::new("wide_default", "Wide Default").width(px(2000.)),
3191 4 => Column::new("wide_explicit", "Wide Explicit")
3193 .max_width(px(2400.))
3194 .width(px(2000.)),
3195 _ => Column::new("inverted", "Inverted")
3197 .min_width(px(200.))
3198 .max_width(px(100.)),
3199 }
3200 }
3201
3202 fn render_td(
3203 &mut self,
3204 _: usize,
3205 _: usize,
3206 _: &mut Window,
3207 _: &mut Context<TableState<Self>>,
3208 ) -> impl IntoElement {
3209 div()
3210 }
3211 }
3212
3213 #[gpui::test]
3214 fn column_resize_bounds_preserve_initial_widths(cx: &mut TestAppContext) {
3215 cx.skip_drawing();
3216 let window = cx.add_window(|window, cx| TableState::new(WidthsDelegate, window, cx));
3217
3218 window
3219 .update(cx, |table, window, cx| {
3220 let widths = |table: &TableState<WidthsDelegate>| {
3221 table
3222 .col_groups
3223 .iter()
3224 .map(|col_group| col_group.width)
3225 .collect::<Vec<_>>()
3226 };
3227 assert_eq!(
3228 widths(table),
3229 [px(40.), px(300.), px(10.), px(2000.), px(2000.), px(100.)]
3230 );
3231
3232 for ix in 0..table.col_groups.len() {
3233 table.resize_cols(ix, px(10000.), window, cx);
3234 }
3235 assert_eq!(
3236 widths(table),
3237 [
3238 px(1200.),
3239 px(120.),
3240 px(1200.),
3241 px(1200.),
3242 px(2400.),
3243 px(100.)
3244 ]
3245 );
3246
3247 for ix in 0..table.col_groups.len() {
3248 table.resize_cols(ix, px(-100.), window, cx);
3249 }
3250 assert_eq!(
3251 widths(table),
3252 [px(80.), px(20.), px(20.), px(20.), px(20.), px(100.)]
3253 );
3254 })
3255 .unwrap();
3256 }
3257}