1use std::{ops::Range, rc::Rc, time::Duration};
2
3use crate::{
4 actions::{Cancel, SelectDown, SelectUp},
5 h_flex,
6 menu::{ContextMenuExt, PopupMenu},
7 scroll::{ScrollableMask, Scrollbar, ScrollbarState},
8 v_flex, ActiveTheme, Icon, IconName, Sizable, Size, StyleSized as _, StyledExt,
9 VirtualListScrollHandle,
10};
11use gpui::{
12 actions, canvas, div, prelude::FluentBuilder, px, uniform_list, App, AppContext, Axis, Bounds,
13 Context, Div, DragMoveEvent, Edges, EventEmitter, FocusHandle, Focusable, InteractiveElement,
14 IntoElement, KeyBinding, ListSizingBehavior, MouseButton, MouseDownEvent, ParentElement,
15 Pixels, Point, Render, ScrollStrategy, ScrollWheelEvent, SharedString,
16 StatefulInteractiveElement as _, Styled, Task, UniformListScrollHandle, Window,
17};
18
19mod column;
20mod delegate;
21mod loading;
22
23pub use column::*;
24pub use delegate::*;
25
26actions!(table, [SelectPrevColumn, SelectNextColumn]);
27
28pub(crate) fn init(cx: &mut App) {
29 let context = Some("Table");
30 cx.bind_keys([
31 KeyBinding::new("escape", Cancel, context),
32 KeyBinding::new("up", SelectUp, context),
33 KeyBinding::new("down", SelectDown, context),
34 KeyBinding::new("left", SelectPrevColumn, context),
35 KeyBinding::new("right", SelectNextColumn, context),
36 ]);
37}
38
39#[derive(Copy, Clone, Debug, PartialEq, Eq)]
40enum SelectionState {
41 Column,
42 Row,
43}
44
45#[derive(Clone)]
46pub enum TableEvent {
47 SelectRow(usize),
49 DoubleClickedRow(usize),
51 SelectColumn(usize),
52 ColumnWidthsChanged(Vec<Pixels>),
53 MoveColumn(usize, usize),
54}
55
56#[derive(Debug, Default)]
58pub struct VisibleRangeState {
59 rows: Range<usize>,
61 cols: Range<usize>,
63}
64
65impl VisibleRangeState {
66 pub fn rows(&self) -> Range<usize> {
68 self.rows.clone()
69 }
70
71 pub fn cols(&self) -> Range<usize> {
73 self.cols.clone()
74 }
75}
76
77pub struct Table<D: TableDelegate> {
78 focus_handle: FocusHandle,
79 delegate: D,
80 bounds: Bounds<Pixels>,
82 fixed_head_cols_bounds: Bounds<Pixels>,
84
85 col_groups: Vec<ColGroup>,
86
87 pub loop_selection: bool,
91 pub col_selectable: bool,
93 pub row_selectable: bool,
95 pub sortable: bool,
97 pub col_resizable: bool,
99 pub col_movable: bool,
101 pub col_fixed: bool,
103
104 pub vertical_scroll_handle: UniformListScrollHandle,
105 pub vertical_scroll_state: ScrollbarState,
106 pub horizontal_scroll_handle: VirtualListScrollHandle,
107 pub horizontal_scroll_state: ScrollbarState,
108
109 scrollbar_visible: Edges<bool>,
110 selected_row: Option<usize>,
111 selection_state: SelectionState,
112 right_clicked_row: Option<usize>,
113 selected_col: Option<usize>,
114
115 resizing_col: Option<usize>,
117
118 stripe: bool,
120 border: bool,
122 size: Size,
124 visible_range: VisibleRangeState,
126
127 _measure: Vec<Duration>,
128 _load_more_task: Task<()>,
129}
130
131impl<D> Table<D>
132where
133 D: TableDelegate,
134{
135 pub fn new(delegate: D, _: &mut Window, cx: &mut Context<Self>) -> Self {
136 let mut this = Self {
137 focus_handle: cx.focus_handle(),
138 delegate,
139 col_groups: Vec::new(),
140 horizontal_scroll_handle: VirtualListScrollHandle::new(),
141 vertical_scroll_handle: UniformListScrollHandle::new(),
142 vertical_scroll_state: ScrollbarState::default(),
143 horizontal_scroll_state: ScrollbarState::default(),
144 selection_state: SelectionState::Row,
145 selected_row: None,
146 right_clicked_row: None,
147 selected_col: None,
148 resizing_col: None,
149 bounds: Bounds::default(),
150 fixed_head_cols_bounds: Bounds::default(),
151 stripe: false,
152 border: true,
153 size: Size::default(),
154 scrollbar_visible: Edges::all(true),
155 visible_range: VisibleRangeState::default(),
156 loop_selection: true,
157 col_selectable: true,
158 row_selectable: true,
159 sortable: true,
160 col_movable: true,
161 col_resizable: true,
162 col_fixed: true,
163 _load_more_task: Task::ready(()),
164 _measure: Vec::new(),
165 };
166
167 this.prepare_col_groups(cx);
168 this
169 }
170
171 pub fn delegate(&self) -> &D {
172 &self.delegate
173 }
174
175 pub fn delegate_mut(&mut self) -> &mut D {
176 &mut self.delegate
177 }
178
179 pub fn stripe(mut self, stripe: bool) -> Self {
181 self.stripe = stripe;
182 self
183 }
184
185 pub fn set_stripe(&mut self, stripe: bool, cx: &mut Context<Self>) {
186 self.stripe = stripe;
187 cx.notify();
188 }
189
190 pub fn border(mut self, border: bool) -> Self {
192 self.border = border;
193 self
194 }
195
196 pub fn loop_selection(mut self, loop_selection: bool) -> Self {
198 self.loop_selection = loop_selection;
199 self
200 }
201
202 pub fn col_movable(mut self, col_movable: bool) -> Self {
204 self.col_movable = col_movable;
205 self
206 }
207
208 pub fn col_resizable(mut self, col_resizable: bool) -> Self {
210 self.col_resizable = col_resizable;
211 self
212 }
213
214 pub fn sortable(mut self, sortable: bool) -> Self {
216 self.sortable = sortable;
217 self
218 }
219
220 pub fn row_selectable(mut self, row_selectable: bool) -> Self {
222 self.row_selectable = row_selectable;
223 self
224 }
225
226 pub fn col_selectable(mut self, col_selectable: bool) -> Self {
228 self.col_selectable = col_selectable;
229 self
230 }
231
232 pub fn set_size(&mut self, size: Size, cx: &mut Context<Self>) {
234 self.size = size;
235 cx.notify();
236 }
237
238 pub fn size(&self) -> Size {
240 self.size
241 }
242
243 pub fn scrollbar_visible(mut self, vertical: bool, horizontal: bool) -> Self {
245 self.scrollbar_visible = Edges {
246 right: vertical,
247 bottom: horizontal,
248 ..Default::default()
249 };
250 self
251 }
252
253 pub fn refresh(&mut self, cx: &mut Context<Self>) {
255 self.prepare_col_groups(cx);
256 }
257
258 fn prepare_col_groups(&mut self, cx: &mut Context<Self>) {
259 self.col_groups = (0..self.delegate.columns_count(cx))
260 .map(|col_ix| {
261 let column = self.delegate().column(col_ix, cx);
262 ColGroup {
263 width: column.width,
264 bounds: Bounds::default(),
265 column: column.clone(),
266 }
267 })
268 .collect();
269 cx.notify();
270 }
271
272 fn fixed_left_cols_count(&self) -> usize {
273 if !self.col_fixed {
274 return 0;
275 }
276
277 self.col_groups
278 .iter()
279 .filter(|col| col.column.fixed == Some(ColumnFixed::Left))
280 .count()
281 }
282
283 pub fn scroll_to_row(&mut self, row_ix: usize, cx: &mut Context<Self>) {
285 self.vertical_scroll_handle
286 .scroll_to_item(row_ix, ScrollStrategy::Top);
287 cx.notify();
288 }
289
290 pub fn scroll_to_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
292 let col_ix = col_ix.saturating_sub(self.fixed_left_cols_count());
293
294 self.horizontal_scroll_handle
295 .scroll_to_item(col_ix, ScrollStrategy::Top);
296 cx.notify();
297 }
298
299 pub fn selected_row(&self) -> Option<usize> {
301 self.selected_row
302 }
303
304 pub fn set_selected_row(&mut self, row_ix: usize, cx: &mut Context<Self>) {
306 self.selection_state = SelectionState::Row;
307 self.right_clicked_row = None;
308 self.selected_row = Some(row_ix);
309 if let Some(row_ix) = self.selected_row {
310 self.vertical_scroll_handle
311 .scroll_to_item(row_ix, ScrollStrategy::Top);
312 }
313 cx.emit(TableEvent::SelectRow(row_ix));
314 cx.notify();
315 }
316
317 pub fn selected_col(&self) -> Option<usize> {
319 self.selected_col
320 }
321
322 pub fn set_selected_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
324 self.selection_state = SelectionState::Column;
325 self.selected_col = Some(col_ix);
326 if let Some(col_ix) = self.selected_col {
327 self.scroll_to_col(col_ix, cx);
328 }
329 cx.emit(TableEvent::SelectColumn(col_ix));
330 cx.notify();
331 }
332
333 pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
335 self.selection_state = SelectionState::Row;
336 self.selected_row = None;
337 self.selected_col = None;
338 cx.notify();
339 }
340
341 pub fn visible_range(&self) -> &VisibleRangeState {
343 &self.visible_range
344 }
345
346 fn on_row_click(
347 &mut self,
348 ev: &MouseDownEvent,
349 row_ix: usize,
350 _: &mut Window,
351 cx: &mut Context<Self>,
352 ) {
353 if ev.button == MouseButton::Right {
354 self.right_clicked_row = Some(row_ix);
355 } else {
356 self.set_selected_row(row_ix, cx);
357
358 if ev.click_count == 2 {
359 cx.emit(TableEvent::DoubleClickedRow(row_ix));
360 }
361 }
362 }
363
364 fn on_col_head_click(&mut self, col_ix: usize, _: &mut Window, cx: &mut Context<Self>) {
365 if !self.col_selectable {
366 return;
367 }
368
369 let Some(col_group) = self.col_groups.get(col_ix) else {
370 return;
371 };
372
373 if !col_group.column.selectable {
374 return;
375 }
376
377 self.set_selected_col(col_ix, cx)
378 }
379
380 fn has_selection(&self) -> bool {
381 self.selected_row.is_some() || self.selected_col.is_some()
382 }
383
384 fn action_cancel(&mut self, _: &Cancel, _: &mut Window, cx: &mut Context<Self>) {
385 if self.has_selection() {
386 self.clear_selection(cx);
387 return;
388 }
389 cx.propagate();
390 }
391
392 fn action_select_prev(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
393 let rows_count = self.delegate.rows_count(cx);
394 if rows_count < 1 {
395 return;
396 }
397
398 let mut selected_row = self.selected_row.unwrap_or(0);
399 if selected_row > 0 {
400 selected_row = selected_row.saturating_sub(1);
401 } else {
402 if self.loop_selection {
403 selected_row = rows_count.saturating_sub(1);
404 }
405 }
406
407 self.set_selected_row(selected_row, cx);
408 }
409
410 fn action_select_next(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
411 let rows_count = self.delegate.rows_count(cx);
412 if rows_count < 1 {
413 return;
414 }
415
416 let selected_row = match self.selected_row {
417 Some(selected_row) if selected_row < rows_count.saturating_sub(1) => selected_row + 1,
418 Some(selected_row) => {
419 if self.loop_selection {
420 0
421 } else {
422 selected_row
423 }
424 }
425 _ => 0,
426 };
427
428 self.set_selected_row(selected_row, cx);
429 }
430
431 fn action_select_prev_col(
432 &mut self,
433 _: &SelectPrevColumn,
434 _: &mut Window,
435 cx: &mut Context<Self>,
436 ) {
437 let mut selected_col = self.selected_col.unwrap_or(0);
438 let columns_count = self.delegate.columns_count(cx);
439 if selected_col > 0 {
440 selected_col = selected_col.saturating_sub(1);
441 } else {
442 if self.loop_selection {
443 selected_col = columns_count.saturating_sub(1);
444 }
445 }
446 self.set_selected_col(selected_col, cx);
447 }
448
449 fn action_select_next_col(
450 &mut self,
451 _: &SelectNextColumn,
452 _: &mut Window,
453 cx: &mut Context<Self>,
454 ) {
455 let mut selected_col = self.selected_col.unwrap_or(0);
456 if selected_col < self.delegate.columns_count(cx).saturating_sub(1) {
457 selected_col += 1;
458 } else {
459 if self.loop_selection {
460 selected_col = 0;
461 }
462 }
463
464 self.set_selected_col(selected_col, cx);
465 }
466
467 fn scroll_table_by_col_resizing(
469 &mut self,
470 mouse_position: Point<Pixels>,
471 col_group: &ColGroup,
472 ) {
473 if mouse_position.x > self.bounds.right() {
475 return;
476 }
477
478 let mut offset = self.horizontal_scroll_handle.offset();
479 let col_bounds = col_group.bounds;
480
481 if mouse_position.x < self.bounds.left()
482 && col_bounds.right() < self.bounds.left() + px(20.)
483 {
484 offset.x += px(1.);
485 } else if mouse_position.x > self.bounds.right()
486 && col_bounds.right() > self.bounds.right() - px(20.)
487 {
488 offset.x -= px(1.);
489 }
490
491 self.horizontal_scroll_handle.set_offset(offset);
492 }
493
494 fn resize_cols(&mut self, ix: usize, size: Pixels, _: &mut Window, cx: &mut Context<Self>) {
497 if !self.col_resizable {
498 return;
499 }
500
501 const MIN_WIDTH: Pixels = px(10.0);
502 const MAX_WIDTH: Pixels = px(1200.0);
503 let Some(col_group) = self.col_groups.get_mut(ix) else {
504 return;
505 };
506
507 if !col_group.is_resizable() {
508 return;
509 }
510 let size = size.floor();
511
512 let old_width = col_group.width;
513 let new_width = size;
514 if new_width < MIN_WIDTH {
515 return;
516 }
517 let changed_width = new_width - old_width;
518 if changed_width > px(-1.0) && changed_width < px(1.0) {
520 return;
521 }
522 col_group.width = new_width.min(MAX_WIDTH);
523
524 cx.notify();
525 }
526
527 fn perform_sort(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
528 if !self.sortable {
529 return;
530 }
531
532 let sort = self.col_groups.get(col_ix).and_then(|g| g.column.sort);
533 if sort.is_none() {
534 return;
535 }
536
537 let sort = sort.unwrap();
538 let sort = match sort {
539 ColumnSort::Ascending => ColumnSort::Default,
540 ColumnSort::Descending => ColumnSort::Ascending,
541 ColumnSort::Default => ColumnSort::Descending,
542 };
543
544 for (ix, col_group) in self.col_groups.iter_mut().enumerate() {
545 if ix == col_ix {
546 col_group.column.sort = Some(sort);
547 } else {
548 if col_group.column.sort.is_some() {
549 col_group.column.sort = Some(ColumnSort::Default);
550 }
551 }
552 }
553
554 self.delegate_mut().perform_sort(col_ix, sort, window, cx);
555
556 cx.notify();
557 }
558
559 fn move_column(
560 &mut self,
561 col_ix: usize,
562 to_ix: usize,
563 window: &mut Window,
564 cx: &mut Context<Self>,
565 ) {
566 if col_ix == to_ix {
567 return;
568 }
569
570 self.delegate.move_column(col_ix, to_ix, window, cx);
571 let col_group = self.col_groups.remove(col_ix);
572 self.col_groups.insert(to_ix, col_group);
573
574 cx.emit(TableEvent::MoveColumn(col_ix, to_ix));
575 cx.notify();
576 }
577
578 fn load_more_if_need(
580 &mut self,
581 rows_count: usize,
582 visible_end: usize,
583 window: &mut Window,
584 cx: &mut Context<Self>,
585 ) {
586 let threshold = self.delegate.load_more_threshold();
587 if visible_end >= rows_count.saturating_sub(threshold) {
589 if !self.delegate.is_eof(cx) {
590 return;
591 }
592
593 self._load_more_task = cx.spawn_in(window, async move |view, window| {
594 _ = view.update_in(window, |view, window, cx| {
595 view.delegate.load_more(window, cx);
596 });
597 });
598 }
599 }
600
601 fn update_visible_range_if_need(
602 &mut self,
603 visible_range: Range<usize>,
604 axis: Axis,
605 window: &mut Window,
606 cx: &mut Context<Self>,
607 ) {
608 if visible_range.len() <= 1 {
611 return;
612 }
613
614 if axis == Axis::Vertical {
615 if self.visible_range.rows == visible_range {
616 return;
617 }
618 self.delegate_mut()
619 .visible_rows_changed(visible_range.clone(), window, cx);
620 self.visible_range.rows = visible_range;
621 } else {
622 if self.visible_range.cols == visible_range {
623 return;
624 }
625 self.delegate_mut()
626 .visible_columns_changed(visible_range.clone(), window, cx);
627 self.visible_range.cols = visible_range;
628 }
629 }
630
631 fn render_cell(&self, col_ix: usize, _window: &mut Window, _cx: &mut Context<Self>) -> Div {
632 let Some(col_group) = self.col_groups.get(col_ix) else {
633 return div();
634 };
635
636 let col_width = col_group.width;
637 let col_padding = col_group.column.paddings;
638
639 div()
640 .w(col_width)
641 .h_full()
642 .flex_shrink_0()
643 .overflow_hidden()
644 .whitespace_nowrap()
645 .table_cell_size(self.size)
646 .map(|this| match col_padding {
647 Some(padding) => this
648 .pl(padding.left)
649 .pr(padding.right)
650 .pt(padding.top)
651 .pb(padding.bottom),
652 None => this,
653 })
654 }
655
656 fn render_col_wrap(&self, col_ix: usize, _: &mut Window, cx: &mut Context<Self>) -> Div {
658 let el = h_flex().h_full();
659 let selectable = self.col_selectable
660 && self
661 .col_groups
662 .get(col_ix)
663 .map(|col_group| col_group.column.selectable)
664 .unwrap_or(false);
665
666 if selectable
667 && self.selected_col == Some(col_ix)
668 && self.selection_state == SelectionState::Column
669 {
670 el.bg(cx.theme().table_active)
671 } else {
672 el
673 }
674 }
675
676 fn render_vertical_scrollbar(
677 &self,
678 _: &mut Window,
679 cx: &mut Context<Self>,
680 ) -> Option<impl IntoElement> {
681 let state = self.vertical_scroll_state.clone();
682
683 Some(
684 div()
685 .occlude()
686 .absolute()
687 .top(self.size.table_row_height())
688 .right_0()
689 .bottom_0()
690 .w(Scrollbar::width())
691 .on_scroll_wheel(cx.listener(|_, _: &ScrollWheelEvent, _, cx| {
692 cx.notify();
693 }))
694 .child(Scrollbar::uniform_scroll(&state, &self.vertical_scroll_handle).max_fps(60)),
695 )
696 }
697
698 fn render_horizontal_scrollbar(
699 &self,
700 _: &mut Window,
701 cx: &mut Context<Self>,
702 ) -> impl IntoElement {
703 let state = self.horizontal_scroll_state.clone();
704
705 div()
706 .occlude()
707 .absolute()
708 .left(self.fixed_head_cols_bounds.size.width)
709 .right_0()
710 .bottom_0()
711 .h(Scrollbar::width())
712 .on_scroll_wheel(cx.listener(|_, _: &ScrollWheelEvent, _, cx| {
713 cx.notify();
714 }))
715 .child(Scrollbar::horizontal(
716 &state,
717 &self.horizontal_scroll_handle,
718 ))
719 }
720
721 fn render_resize_handle(
722 &self,
723 ix: usize,
724 _: &mut Window,
725 cx: &mut Context<Self>,
726 ) -> impl IntoElement {
727 const HANDLE_SIZE: Pixels = px(2.);
728
729 let resizable = self.col_resizable
730 && self
731 .col_groups
732 .get(ix)
733 .map(|col| col.is_resizable())
734 .unwrap_or(false);
735 if !resizable {
736 return div().into_any_element();
737 }
738
739 let group_id = SharedString::from(format!("resizable-handle:{}", ix));
740
741 h_flex()
742 .id(("resizable-handle", ix))
743 .group(group_id.clone())
744 .occlude()
745 .cursor_col_resize()
746 .h_full()
747 .w(HANDLE_SIZE)
748 .ml(-(HANDLE_SIZE))
749 .justify_end()
750 .items_center()
751 .child(
752 div()
753 .h_full()
754 .justify_center()
755 .bg(cx.theme().table_row_border)
756 .group_hover(group_id, |this| this.bg(cx.theme().border).h_full())
757 .w(px(1.)),
758 )
759 .on_drag_move(
760 cx.listener(move |view, e: &DragMoveEvent<ResizeColumn>, window, cx| {
761 match e.drag(cx) {
762 ResizeColumn((entity_id, ix)) => {
763 if cx.entity_id() != *entity_id {
764 return;
765 }
766
767 let ix = *ix;
774 view.resizing_col = Some(ix);
775
776 let col_group = view
777 .col_groups
778 .get(ix)
779 .expect("BUG: invalid col index")
780 .clone();
781
782 view.resize_cols(
783 ix,
784 e.event.position.x - HANDLE_SIZE - col_group.bounds.left(),
785 window,
786 cx,
787 );
788
789 view.scroll_table_by_col_resizing(e.event.position, &col_group);
791 }
792 };
793 }),
794 )
795 .on_drag(ResizeColumn((cx.entity_id(), ix)), |drag, _, _, cx| {
796 cx.stop_propagation();
797 cx.new(|_| drag.clone())
798 })
799 .on_mouse_up_out(
800 MouseButton::Left,
801 cx.listener(|view, _, _, cx| {
802 if view.resizing_col.is_none() {
803 return;
804 }
805
806 view.resizing_col = None;
807
808 let new_widths = view.col_groups.iter().map(|g| g.width).collect();
809 cx.emit(TableEvent::ColumnWidthsChanged(new_widths));
810 cx.notify();
811 }),
812 )
813 .into_any_element()
814 }
815
816 fn render_sort_icon(
817 &self,
818 col_ix: usize,
819 col_group: &ColGroup,
820 _: &mut Window,
821 cx: &mut Context<Self>,
822 ) -> Option<impl IntoElement> {
823 if !self.sortable {
824 return None;
825 }
826
827 let Some(sort) = col_group.column.sort else {
828 return None;
829 };
830
831 let (icon, is_on) = match sort {
832 ColumnSort::Ascending => (IconName::SortAscending, true),
833 ColumnSort::Descending => (IconName::SortDescending, true),
834 ColumnSort::Default => (IconName::ChevronsUpDown, false),
835 };
836
837 Some(
838 div()
839 .id(("icon-sort", col_ix))
840 .p(px(2.))
841 .rounded(cx.theme().radius / 2.)
842 .map(|this| match is_on {
843 true => this,
844 false => this.opacity(0.5),
845 })
846 .hover(|this| this.bg(cx.theme().secondary).opacity(7.))
847 .active(|this| this.bg(cx.theme().secondary_active).opacity(1.))
848 .on_click(
849 cx.listener(move |table, _, window, cx| table.perform_sort(col_ix, window, cx)),
850 )
851 .child(
852 Icon::new(icon)
853 .size_3()
854 .text_color(cx.theme().secondary_foreground),
855 ),
856 )
857 }
858
859 fn render_th(
864 &self,
865 col_ix: usize,
866 window: &mut Window,
867 cx: &mut Context<Self>,
868 ) -> impl IntoElement {
869 let entity_id = cx.entity_id();
870 let col_group = self.col_groups.get(col_ix).expect("BUG: invalid col index");
871
872 let movable = self.col_movable && col_group.column.movable;
873 let paddings = col_group.column.paddings;
874 let name = col_group.column.name.clone();
875
876 h_flex()
877 .h_full()
878 .child(
879 self.render_cell(col_ix, window, cx)
880 .id(("col-header", col_ix))
881 .on_mouse_down(
882 MouseButton::Left,
883 cx.listener(move |this, _, window, cx| {
884 this.on_col_head_click(col_ix, window, cx);
885 }),
886 )
887 .child(
888 h_flex()
889 .size_full()
890 .justify_between()
891 .items_center()
892 .child(self.delegate.render_th(col_ix, window, cx))
893 .when_some(paddings, |this, paddings| {
894 let offset_pr =
896 self.size.table_cell_padding().right - paddings.right;
897 this.pr(offset_pr.max(px(0.)))
898 })
899 .children(self.render_sort_icon(col_ix, &col_group, window, cx)),
900 )
901 .when(movable, |this| {
902 this.on_drag(
903 DragColumn {
904 entity_id,
905 col_ix,
906 name,
907 width: col_group.width,
908 },
909 |drag, _, _, cx| {
910 cx.stop_propagation();
911 cx.new(|_| drag.clone())
912 },
913 )
914 .drag_over::<DragColumn>(|this, _, _, cx| {
915 this.rounded_l_none()
916 .border_l_2()
917 .border_r_0()
918 .border_color(cx.theme().drag_border)
919 })
920 .on_drop(cx.listener(
921 move |table, drag: &DragColumn, window, cx| {
922 if drag.entity_id != cx.entity_id() {
924 return;
925 }
926
927 table.move_column(drag.col_ix, col_ix, window, cx);
928 },
929 ))
930 }),
931 )
932 .child(self.render_resize_handle(col_ix, window, cx))
934 .child({
936 let view = cx.entity().clone();
937 canvas(
938 move |bounds, _, cx| {
939 view.update(cx, |r, _| r.col_groups[col_ix].bounds = bounds)
940 },
941 |_, _, _, _| {},
942 )
943 .absolute()
944 .size_full()
945 })
946 }
947
948 fn render_table_head(
949 &mut self,
950 left_columns_count: usize,
951 window: &mut Window,
952 cx: &mut Context<Self>,
953 ) -> impl IntoElement {
954 let view = cx.entity().clone();
955 let horizontal_scroll_handle = self.horizontal_scroll_handle.clone();
956
957 if left_columns_count == 0 {
959 self.fixed_head_cols_bounds = Bounds::default();
960 }
961
962 h_flex()
963 .w_full()
964 .h(self.size.table_row_height())
965 .flex_shrink_0()
966 .border_b_1()
967 .border_color(cx.theme().border)
968 .text_color(cx.theme().table_head_foreground)
969 .when(left_columns_count > 0, |this| {
970 let view = view.clone();
971 this.child(
973 h_flex()
974 .relative()
975 .h_full()
976 .bg(cx.theme().table_head)
977 .children(
978 self.col_groups
979 .iter()
980 .filter(|col| col.column.fixed == Some(ColumnFixed::Left))
981 .enumerate()
982 .map(|(col_ix, _)| self.render_th(col_ix, window, cx)),
983 )
984 .child(
985 div()
987 .absolute()
988 .top_0()
989 .right_0()
990 .bottom_0()
991 .w_0()
992 .flex_shrink_0()
993 .border_r_1()
994 .border_color(cx.theme().border),
995 )
996 .child(
997 canvas(
998 move |bounds, _, cx| {
999 view.update(cx, |r, _| r.fixed_head_cols_bounds = bounds)
1000 },
1001 |_, _, _, _| {},
1002 )
1003 .absolute()
1004 .size_full(),
1005 ),
1006 )
1007 })
1008 .child(
1009 h_flex()
1011 .id("table-head")
1012 .size_full()
1013 .overflow_scroll()
1014 .relative()
1015 .track_scroll(&horizontal_scroll_handle)
1016 .bg(cx.theme().table_head)
1017 .child(
1018 h_flex()
1019 .relative()
1020 .children(
1021 self.col_groups
1022 .iter()
1023 .skip(left_columns_count)
1024 .enumerate()
1025 .map(|(col_ix, _)| {
1026 self.render_th(left_columns_count + col_ix, window, cx)
1027 }),
1028 )
1029 .child(self.delegate.render_last_empty_col(window, cx)),
1030 ),
1031 )
1032 }
1033
1034 #[allow(clippy::too_many_arguments)]
1035 fn render_table_row(
1036 &mut self,
1037 row_ix: usize,
1038 rows_count: usize,
1039 left_columns_count: usize,
1040 col_sizes: Rc<Vec<gpui::Size<Pixels>>>,
1041 columns_count: usize,
1042 extra_rows_count: usize,
1043 window: &mut Window,
1044 cx: &mut Context<Self>,
1045 ) -> impl IntoElement {
1046 let horizontal_scroll_handle = self.horizontal_scroll_handle.clone();
1047 let is_stripe_row = self.stripe && row_ix % 2 != 0;
1048 let is_selected = self.selected_row == Some(row_ix);
1049 let view = cx.entity().clone();
1050
1051 if row_ix < rows_count {
1052 let is_last_row = row_ix == rows_count - 1;
1053 let table_is_filled = extra_rows_count == 0;
1054 let need_render_border = if is_last_row {
1055 if is_selected {
1056 true
1057 } else if table_is_filled {
1058 false
1059 } else {
1060 !self.stripe
1061 }
1062 } else {
1063 true
1064 };
1065
1066 let mut tr = self.delegate.render_tr(row_ix, window, cx);
1067 let style = tr.style().clone();
1068
1069 tr.h_flex()
1070 .w_full()
1071 .h(self.size.table_row_height())
1072 .when(need_render_border, |this| {
1073 this.border_b_1().border_color(cx.theme().table_row_border)
1074 })
1075 .when(is_stripe_row, |this| this.bg(cx.theme().table_even))
1076 .refine_style(&style)
1077 .hover(|this| {
1078 if is_selected || self.right_clicked_row == Some(row_ix) {
1079 this
1080 } else {
1081 this.bg(cx.theme().table_hover)
1082 }
1083 })
1084 .when(left_columns_count > 0, |this| {
1085 this.child(
1087 h_flex()
1088 .relative()
1089 .h_full()
1090 .children({
1091 let mut items = Vec::with_capacity(left_columns_count);
1092
1093 (0..left_columns_count).for_each(|col_ix| {
1094 items.push(self.render_col_wrap(col_ix, window, cx).child(
1095 self.render_cell(col_ix, window, cx).child(
1096 self.measure_render_td(row_ix, col_ix, window, cx),
1097 ),
1098 ));
1099 });
1100
1101 items
1102 })
1103 .child(
1104 div()
1106 .absolute()
1107 .top_0()
1108 .right_0()
1109 .bottom_0()
1110 .w_0()
1111 .flex_shrink_0()
1112 .border_r_1()
1113 .border_color(cx.theme().border),
1114 ),
1115 )
1116 })
1117 .child(
1118 h_flex()
1119 .flex_1()
1120 .h_full()
1121 .overflow_hidden()
1122 .relative()
1123 .child(
1124 crate::virtual_list::virtual_list(
1125 view,
1126 row_ix,
1127 Axis::Horizontal,
1128 col_sizes,
1129 {
1130 move |table, visible_range: Range<usize>, window, cx| {
1131 table.update_visible_range_if_need(
1132 visible_range.clone(),
1133 Axis::Horizontal,
1134 window,
1135 cx,
1136 );
1137
1138 let mut items = Vec::with_capacity(
1139 visible_range.end - visible_range.start,
1140 );
1141
1142 visible_range.for_each(|col_ix| {
1143 let col_ix = col_ix + left_columns_count;
1144 let el =
1145 table.render_col_wrap(col_ix, window, cx).child(
1146 table.render_cell(col_ix, window, cx).child(
1147 table.measure_render_td(
1148 row_ix, col_ix, window, cx,
1149 ),
1150 ),
1151 );
1152
1153 items.push(el);
1154 });
1155
1156 items
1157 }
1158 },
1159 )
1160 .with_scroll_handle(&self.horizontal_scroll_handle),
1161 )
1162 .child(self.delegate.render_last_empty_col(window, cx)),
1163 )
1164 .when_some(self.selected_row, |this, _| {
1166 this.when(
1167 is_selected && self.selection_state == SelectionState::Row,
1168 |this| {
1169 this.border_color(gpui::transparent_white()).child(
1170 div()
1171 .top(if row_ix == 0 { px(0.) } else { px(-1.) })
1172 .left(px(0.))
1173 .right(px(0.))
1174 .bottom(px(-1.))
1175 .absolute()
1176 .bg(cx.theme().table_active)
1177 .border_1()
1178 .border_color(cx.theme().table_active_border),
1179 )
1180 },
1181 )
1182 })
1183 .when(self.right_clicked_row == Some(row_ix), |this| {
1185 this.border_color(gpui::transparent_white()).child(
1186 div()
1187 .top(if row_ix == 0 { px(0.) } else { px(-1.) })
1188 .left(px(0.))
1189 .right(px(0.))
1190 .bottom(px(-1.))
1191 .absolute()
1192 .border_1()
1193 .border_color(cx.theme().selection),
1194 )
1195 })
1196 .on_mouse_down(
1197 MouseButton::Left,
1198 cx.listener(move |this, ev, window, cx| {
1199 this.on_row_click(ev, row_ix, window, cx);
1200 }),
1201 )
1202 .on_mouse_down(
1203 MouseButton::Right,
1204 cx.listener(move |this, ev, window, cx| {
1205 this.on_row_click(ev, row_ix, window, cx);
1206 }),
1207 )
1208 } else {
1209 self.delegate
1211 .render_tr(row_ix, window, cx)
1212 .h_flex()
1213 .w_full()
1214 .h_full()
1215 .border_t_1()
1216 .border_color(cx.theme().table_row_border)
1217 .when(is_stripe_row, |this| this.bg(cx.theme().table_even))
1218 .children((0..columns_count).map(|col_ix| {
1219 h_flex()
1220 .left(horizontal_scroll_handle.offset().x)
1221 .child(self.render_cell(col_ix, window, cx))
1222 }))
1223 .child(self.delegate.render_last_empty_col(window, cx))
1224 }
1225 }
1226
1227 fn calculate_extra_rows_needed(&self, rows_count: usize) -> usize {
1229 let mut extra_rows_needed = 0;
1230
1231 let row_height = self.size.table_row_height();
1232 let total_height = self
1233 .vertical_scroll_handle
1234 .0
1235 .borrow()
1236 .base_handle
1237 .bounds()
1238 .size
1239 .height;
1240
1241 let actual_height = row_height * rows_count as f32;
1242 let remaining_height = total_height - actual_height;
1243
1244 if remaining_height > px(0.) {
1245 extra_rows_needed = (remaining_height / row_height).ceil() as usize;
1246 }
1247
1248 extra_rows_needed
1249 }
1250
1251 #[inline]
1252 fn measure_render_td(
1253 &mut self,
1254 row_ix: usize,
1255 col_ix: usize,
1256 window: &mut Window,
1257 cx: &mut Context<Self>,
1258 ) -> impl IntoElement {
1259 if !crate::measure_enable() {
1260 return self
1261 .delegate
1262 .render_td(row_ix, col_ix, window, cx)
1263 .into_any_element();
1264 }
1265
1266 let start = std::time::Instant::now();
1267 let el = self.delegate.render_td(row_ix, col_ix, window, cx);
1268 self._measure.push(start.elapsed());
1269 el.into_any_element()
1270 }
1271
1272 fn measure(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
1273 if !crate::measure_enable() {
1274 return;
1275 }
1276
1277 if self._measure.len() > 0 {
1279 let total = self
1280 ._measure
1281 .iter()
1282 .fold(Duration::default(), |acc, d| acc + *d);
1283 let avg = total / self._measure.len() as u32;
1284 eprintln!(
1285 "last render {} cells total: {:?}, avg: {:?}",
1286 self._measure.len(),
1287 total,
1288 avg,
1289 );
1290 }
1291 self._measure.clear();
1292 }
1293}
1294
1295impl<D> Sizable for Table<D>
1296where
1297 D: TableDelegate,
1298{
1299 fn with_size(mut self, size: impl Into<Size>) -> Self {
1300 self.size = size.into();
1301 self
1302 }
1303}
1304impl<D> Focusable for Table<D>
1305where
1306 D: TableDelegate,
1307{
1308 fn focus_handle(&self, _cx: &gpui::App) -> FocusHandle {
1309 self.focus_handle.clone()
1310 }
1311}
1312impl<D> EventEmitter<TableEvent> for Table<D> where D: TableDelegate {}
1313
1314impl<D> Render for Table<D>
1315where
1316 D: TableDelegate,
1317{
1318 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1319 self.measure(window, cx);
1320
1321 let view = cx.entity().clone();
1322 let vertical_scroll_handle = self.vertical_scroll_handle.clone();
1323 let horizontal_scroll_handle = self.horizontal_scroll_handle.clone();
1324 let columns_count: usize = self.delegate.columns_count(cx);
1325 let left_columns_count = self
1326 .col_groups
1327 .iter()
1328 .filter(|col| self.col_fixed && col.column.fixed == Some(ColumnFixed::Left))
1329 .count();
1330 let rows_count = self.delegate.rows_count(cx);
1331 let loading = self.delegate.loading(cx);
1332 let extra_rows_count = self.calculate_extra_rows_needed(rows_count);
1333 let render_rows_count = if self.stripe {
1334 rows_count + extra_rows_count
1335 } else {
1336 rows_count
1337 };
1338
1339 let inner_table = v_flex()
1340 .key_context("Table")
1341 .id("table")
1342 .track_focus(&self.focus_handle)
1343 .on_action(cx.listener(Self::action_cancel))
1344 .on_action(cx.listener(Self::action_select_next))
1345 .on_action(cx.listener(Self::action_select_prev))
1346 .on_action(cx.listener(Self::action_select_next_col))
1347 .on_action(cx.listener(Self::action_select_prev_col))
1348 .size_full()
1349 .overflow_hidden()
1350 .child(self.render_table_head(left_columns_count, window, cx))
1351 .context_menu({
1352 let view = view.clone();
1353 move |this, window: &mut Window, cx: &mut Context<PopupMenu>| {
1354 if let Some(row_ix) = view.read(cx).right_clicked_row {
1355 view.read(cx)
1356 .delegate
1357 .context_menu(row_ix, this, window, cx)
1358 } else {
1359 this
1360 }
1361 }
1362 })
1363 .map(|this| {
1364 if rows_count == 0 {
1365 this.child(
1366 div()
1367 .size_full()
1368 .child(self.delegate.render_empty(window, cx)),
1369 )
1370 } else {
1371 this.child(
1372 h_flex().id("table-body").flex_grow().size_full().child(
1373 uniform_list(
1374 "table-uniform-list",
1375 render_rows_count,
1376 cx.processor(
1377 move |table, visible_range: Range<usize>, window, cx| {
1378 let col_sizes: Rc<Vec<gpui::Size<Pixels>>> = Rc::new(
1381 table
1382 .col_groups
1383 .iter()
1384 .skip(left_columns_count)
1385 .map(|col| col.bounds.size)
1386 .collect(),
1387 );
1388
1389 table.load_more_if_need(
1390 rows_count,
1391 visible_range.end,
1392 window,
1393 cx,
1394 );
1395 table.update_visible_range_if_need(
1396 visible_range.clone(),
1397 Axis::Vertical,
1398 window,
1399 cx,
1400 );
1401
1402 if visible_range.end > rows_count {
1403 table.scroll_to_row(
1404 std::cmp::min(
1405 visible_range.start,
1406 rows_count.saturating_sub(1),
1407 ),
1408 cx,
1409 );
1410 }
1411
1412 let mut items = Vec::with_capacity(
1413 visible_range.end.saturating_sub(visible_range.start),
1414 );
1415
1416 visible_range.for_each(|row_ix| {
1418 items.push(table.render_table_row(
1420 row_ix,
1421 rows_count,
1422 left_columns_count,
1423 col_sizes.clone(),
1424 columns_count,
1425 extra_rows_count,
1426 window,
1427 cx,
1428 ));
1429 });
1430
1431 items
1432 },
1433 ),
1434 )
1435 .flex_grow()
1436 .size_full()
1437 .with_sizing_behavior(ListSizingBehavior::Auto)
1438 .track_scroll(vertical_scroll_handle)
1439 .into_any_element(),
1440 ),
1441 )
1442 }
1443 });
1444
1445 let view = cx.entity().clone();
1446 div()
1447 .size_full()
1448 .when(self.border, |this| {
1449 this.rounded(cx.theme().radius)
1450 .border_1()
1451 .border_color(cx.theme().border)
1452 })
1453 .bg(cx.theme().table)
1454 .when(loading, |this| {
1455 this.child(self.delegate().render_loading(self.size, window, cx))
1456 })
1457 .when(!loading, |this| {
1458 this.child(inner_table)
1459 .child(ScrollableMask::new(
1460 cx.entity().entity_id(),
1461 Axis::Horizontal,
1462 &horizontal_scroll_handle,
1463 ))
1464 .when(self.right_clicked_row.is_some(), |this| {
1465 this.on_mouse_down_out(cx.listener(|this, _, _, cx| {
1466 this.right_clicked_row = None;
1467 cx.notify();
1468 }))
1469 })
1470 })
1471 .child(canvas(
1472 move |bounds, _, cx| view.update(cx, |r, _| r.bounds = bounds),
1473 |_, _, _, _| {},
1474 ))
1475 .when(!window.is_inspector_picking(cx), |this| {
1476 this.child(
1477 div()
1478 .absolute()
1479 .top_0()
1480 .size_full()
1481 .when(self.scrollbar_visible.bottom, |this| {
1482 this.child(self.render_horizontal_scrollbar(window, cx))
1483 })
1484 .when(self.scrollbar_visible.right && rows_count > 0, |this| {
1485 this.children(self.render_vertical_scrollbar(window, cx))
1486 }),
1487 )
1488 })
1489 }
1490}