1use std::{ops::Range, rc::Rc, time::Duration};
2
3use crate::{
4 ActiveTheme, ElementExt, Icon, IconName, StyleSized as _, StyledExt, VirtualListScrollHandle,
5 h_flex, v_flex,
6};
7use crate::{
8 AppContext, Axis, Bounds, ClickEvent, Context, Div, DragMoveEvent, EventEmitter, FocusHandle,
9 Focusable, InteractiveElement, IntoElement, ListSizingBehavior, MouseButton, MouseDownEvent,
10 ParentElement, Pixels, Point, Render, ScrollStrategy, ScrollableMask, Scrollbar, SharedString,
11 Size, Stateful, StatefulInteractiveElement as _, Styled, Task, UniformListScrollHandle, Window,
12 div, prelude::FluentBuilder, px, transparent_white, uniform_list,
13};
14use crate::{
15 menu::PopupMenu,
16 menu::{
17 Cancel, ContextMenuExt, SelectDown, SelectFirst, SelectLast, SelectNextColumn,
18 SelectPageDown, SelectPageUp, SelectPrevColumn, SelectUp,
19 },
20};
21
22use super::*;
23
24#[inline]
29#[allow(clippy::panic)] fn invariant<T>(value: Option<T>, message: &str) -> T {
31 match value {
32 Some(value) => value,
33 None => panic!("{message}"),
34 }
35}
36
37#[inline]
41fn measure_enable() -> bool {
42 std::env::var("ZED_MEASUREMENTS").is_ok() || std::env::var("rgpui_MEASUREMENTS").is_ok()
43}
44
45#[derive(Copy, Clone, Debug, PartialEq, Eq)]
46enum SelectionMode {
47 Column,
48 Row,
49 Cell,
50}
51
52impl SelectionMode {
53 #[inline(always)]
54 fn is_row(&self) -> bool {
55 matches!(self, SelectionMode::Row)
56 }
57
58 #[inline(always)]
59 fn is_column(&self) -> bool {
60 matches!(self, SelectionMode::Column)
61 }
62
63 #[inline(always)]
64 fn is_cell(&self) -> bool {
65 matches!(self, SelectionMode::Cell)
66 }
67}
68
69#[derive(Clone)]
71pub enum TableEvent {
72 SelectRow(usize),
74 DoubleClickedRow(usize),
76 SelectColumn(usize),
78 SelectCell(usize, usize),
85 DoubleClickedCell(usize, usize),
92 ColumnWidthsChanged(Vec<Pixels>),
96 MoveColumn(usize, usize),
101 RightClickedRow(Option<usize>),
106 RightClickedCell(usize, usize),
114 ClearSelection,
118}
119
120#[derive(Debug, Default)]
122pub struct TableVisibleRange {
123 rows: Range<usize>,
125 cols: Range<usize>,
127}
128
129impl TableVisibleRange {
130 pub fn rows(&self) -> &Range<usize> {
132 &self.rows
133 }
134
135 pub fn cols(&self) -> &Range<usize> {
137 &self.cols
138 }
139}
140
141#[derive(Clone)]
191pub(crate) struct HeaderCell {
192 pub label: SharedString,
193 pub width: Pixels,
194 col_span: usize,
195 is_leaf: bool,
196 leaf_col_ix: Option<usize>,
197 start_leaf_col_ix: usize,
198}
199
200pub struct TableState<D: TableDelegate> {
202 focus_handle: FocusHandle,
203 delegate: D,
204 pub(super) options: TableOptions,
205 bounds: Bounds<Pixels>,
207 fixed_head_cols_bounds: Bounds<Pixels>,
209
210 col_groups: Vec<ColGroup>,
211 header_layout: Vec<Vec<HeaderCell>>,
212
213 pub loop_selection: bool,
217 pub col_selectable: bool,
219 pub row_selectable: bool,
221 pub cell_selectable: bool,
230 pub row_header: bool,
238 pub sortable: bool,
240 pub col_resizable: bool,
242 pub col_movable: bool,
244 pub col_fixed: bool,
246
247 pub vertical_scroll_handle: UniformListScrollHandle,
249 pub horizontal_scroll_handle: VirtualListScrollHandle,
251
252 selected_row: Option<usize>,
253 selection_mode: SelectionMode,
254 right_clicked_row: Option<usize>,
255 right_clicked_cell: Option<(usize, usize)>,
256 selected_col: Option<usize>,
257 selected_cell: Option<(usize, usize)>,
258
259 resizing_col: Option<usize>,
261
262 col_drag_gap: Option<usize>,
265
266 visible_range: TableVisibleRange,
268
269 _measure: Vec<Duration>,
270 _load_more_task: Task<()>,
271}
272
273impl<D> TableState<D>
274where
275 D: TableDelegate,
276{
277 pub fn new(delegate: D, _: &mut Window, cx: &mut Context<Self>) -> Self {
279 let mut this = Self {
280 focus_handle: cx.focus_handle().tab_stop(true),
281 options: TableOptions::default(),
282 delegate,
283 col_groups: Vec::new(),
284 header_layout: Vec::new(),
285 horizontal_scroll_handle: VirtualListScrollHandle::new(),
286 vertical_scroll_handle: UniformListScrollHandle::new(),
287 selection_mode: SelectionMode::Row,
288 selected_row: None,
289 right_clicked_row: None,
290 right_clicked_cell: None,
291 selected_col: None,
292 selected_cell: None,
293 resizing_col: None,
294 col_drag_gap: None,
295 bounds: Bounds::default(),
296 fixed_head_cols_bounds: Bounds::default(),
297 visible_range: TableVisibleRange::default(),
298 loop_selection: true,
299 col_selectable: true,
300 row_selectable: true,
301 cell_selectable: false,
302 row_header: true,
303 sortable: true,
304 col_movable: true,
305 col_resizable: true,
306 col_fixed: true,
307 _load_more_task: Task::ready(()),
308 _measure: Vec::new(),
309 };
310
311 this.prepare_col_groups(cx);
312 this
313 }
314
315 pub fn delegate(&self) -> &D {
317 &self.delegate
318 }
319
320 pub fn delegate_mut(&mut self) -> &mut D {
322 &mut self.delegate
323 }
324
325 pub fn loop_selection(mut self, loop_selection: bool) -> Self {
327 self.loop_selection = loop_selection;
328 self
329 }
330
331 pub fn col_movable(mut self, col_movable: bool) -> Self {
333 self.col_movable = col_movable;
334 self
335 }
336
337 pub fn col_resizable(mut self, col_resizable: bool) -> Self {
339 self.col_resizable = col_resizable;
340 self
341 }
342
343 pub fn sortable(mut self, sortable: bool) -> Self {
345 self.sortable = sortable;
346 self
347 }
348
349 pub fn row_selectable(mut self, row_selectable: bool) -> Self {
351 self.row_selectable = row_selectable;
352 self
353 }
354
355 pub fn col_selectable(mut self, col_selectable: bool) -> Self {
357 self.col_selectable = col_selectable;
358 self
359 }
360
361 pub fn cell_selectable(mut self, cell_selectable: bool) -> Self {
379 self.cell_selectable = cell_selectable;
380 self
381 }
382
383 pub fn row_header(mut self, row_header: bool) -> Self {
392 self.row_header = row_header;
393 self
394 }
395
396 pub fn refresh(&mut self, cx: &mut Context<Self>) {
398 self.prepare_col_groups(cx);
399 }
400
401 pub fn scroll_to_row(&mut self, row_ix: usize, cx: &mut Context<Self>) {
403 self.vertical_scroll_handle
404 .scroll_to_item(row_ix, ScrollStrategy::Top);
405 cx.notify();
406 }
407
408 pub fn scroll_to_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
410 let col_ix = col_ix.saturating_sub(self.fixed_left_cols_count());
411
412 self.horizontal_scroll_handle
413 .scroll_to_item(col_ix, ScrollStrategy::Top);
414 cx.notify();
415 }
416
417 pub fn selected_row(&self) -> Option<usize> {
419 self.selected_row
420 }
421
422 pub fn set_selected_row(&mut self, row_ix: usize, cx: &mut Context<Self>) {
424 let is_down = match self.selected_row {
425 Some(selected_row) => row_ix > selected_row,
426 None => true,
427 };
428
429 cx.stop_propagation();
430 self.selection_mode = SelectionMode::Row;
431 self.right_clicked_row = None;
432 self.selected_row = Some(row_ix);
433 if let Some(row_ix) = self.selected_row {
434 self.vertical_scroll_handle.scroll_to_item(
435 row_ix,
436 if is_down {
437 ScrollStrategy::Bottom
438 } else {
439 ScrollStrategy::Top
440 },
441 );
442 }
443 cx.emit(TableEvent::SelectRow(row_ix));
444 cx.emit(TableEvent::RightClickedRow(None));
445 cx.notify();
446 }
447
448 pub fn right_clicked_row(&self) -> Option<usize> {
450 self.right_clicked_row
451 }
452
453 pub fn set_right_clicked_row(&mut self, row: Option<usize>, cx: &mut Context<Self>) {
458 self.right_clicked_row = row;
459 cx.notify();
460 }
461
462 pub fn selected_col(&self) -> Option<usize> {
464 self.selected_col
465 }
466
467 pub fn set_selected_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
469 self.selection_mode = SelectionMode::Column;
470 self.selected_col = Some(col_ix);
471 if let Some(col_ix) = self.selected_col {
472 self.scroll_to_col(col_ix, cx);
473 }
474 cx.emit(TableEvent::SelectColumn(col_ix));
475 cx.notify();
476 }
477
478 pub fn selected_cell(&self) -> Option<(usize, usize)> {
490 self.selected_cell
491 }
492
493 pub fn set_selected_cell(&mut self, row_ix: usize, col_ix: usize, cx: &mut Context<Self>) {
509 self.selection_mode = SelectionMode::Cell;
510 self.selected_cell = Some((row_ix, col_ix));
511
512 self.vertical_scroll_handle
514 .scroll_to_item(row_ix, ScrollStrategy::Center);
515 self.scroll_to_col(col_ix, cx);
516
517 cx.emit(TableEvent::SelectCell(row_ix, col_ix));
518 cx.notify();
519 }
520
521 pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
523 self.selection_mode = SelectionMode::Row;
524 self.selected_row = None;
525 self.selected_col = None;
526 self.selected_cell = None;
527 cx.emit(TableEvent::ClearSelection);
528 cx.notify();
529 }
530
531 pub fn visible_range(&self) -> &TableVisibleRange {
535 &self.visible_range
536 }
537
538 pub fn dump(&self, cx: &App) -> (Vec<String>, Vec<Vec<String>>) {
542 let columns_count = self.delegate.columns_count(cx);
544 let mut headers = Vec::with_capacity(columns_count);
545 for col_ix in 0..columns_count {
546 let column = self.delegate.column(col_ix, cx);
547 headers.push(column.name.to_string());
548 }
549
550 let rows_count = self.delegate.rows_count(cx);
552 let mut rows = Vec::with_capacity(rows_count);
553 for row_ix in 0..rows_count {
554 let mut row = Vec::with_capacity(columns_count);
555 for col_ix in 0..columns_count {
556 row.push(self.delegate.cell_text(row_ix, col_ix, cx));
557 }
558 rows.push(row);
559 }
560
561 (headers, rows)
562 }
563
564 pub fn refresh_header_layout(&mut self, cx: &mut Context<Self>) {
568 self.update_header_layout(cx);
569 cx.notify();
570 }
571
572 fn prepare_col_groups(&mut self, cx: &mut Context<Self>) {
573 self.col_groups = (0..self.delegate.columns_count(cx))
574 .map(|col_ix| {
575 let column = self.delegate().column(col_ix, cx);
576 ColGroup {
577 width: column.width,
578 bounds: Bounds::default(),
579 column,
580 }
581 })
582 .collect();
583
584 self.update_header_layout(cx);
585 }
586
587 fn update_header_layout(&mut self, cx: &mut Context<Self>) {
588 let group_rows = self.delegate.group_headers(cx);
589
590 let mut layout = match group_rows.as_ref() {
591 Some(rows) => Vec::with_capacity(rows.len() + 1),
592 None => Vec::with_capacity(1),
593 };
594
595 if let Some(group_rows) = group_rows {
596 for row in group_rows {
597 let mut cell_row = Vec::with_capacity(row.len());
598 let mut current_leaf_ix = 0;
599 for group in row {
600 let mut width = px(0.);
601 let start_leaf_col_ix = current_leaf_ix;
602 for i in 0..group.span {
603 if current_leaf_ix + i < self.col_groups.len() {
604 width += self.col_groups[current_leaf_ix + i].width;
605 }
606 }
607 current_leaf_ix += group.span;
608 cell_row.push(HeaderCell {
609 label: group.label.clone(),
610 width,
611 col_span: group.span,
612 is_leaf: false,
613 leaf_col_ix: None,
614 start_leaf_col_ix,
615 });
616 }
617 layout.push(cell_row);
618 }
619 }
620
621 let mut leaf_row = Vec::with_capacity(self.col_groups.len());
622 for (ix, group) in self.col_groups.iter().enumerate() {
623 leaf_row.push(HeaderCell {
624 label: group.column.name.clone(),
625 width: group.width,
626 col_span: 1,
627 is_leaf: true,
628 leaf_col_ix: Some(ix),
629 start_leaf_col_ix: ix,
630 });
631 }
632 layout.push(leaf_row);
633
634 self.header_layout = layout;
635 }
636
637 fn fixed_left_cols_count(&self) -> usize {
638 if !self.col_fixed {
639 return 0;
640 }
641
642 self.col_groups
643 .iter()
644 .filter(|col| col.column.fixed == Some(ColumnFixed::Left))
645 .count()
646 }
647
648 fn page_item_count(&self) -> usize {
649 let row_height = self.options.size.table_row_height();
650 let height = self.bounds.size.height;
651 let count = (height / row_height).floor() as usize;
652 count.saturating_sub(1).max(1)
653 }
654
655 fn on_row_right_click(
656 &mut self,
657 _: &MouseDownEvent,
658 row_ix: Option<usize>,
659 _: &mut Window,
660 cx: &mut Context<Self>,
661 ) {
662 self.right_clicked_row = row_ix;
663 self.right_clicked_cell = None;
664 cx.emit(TableEvent::RightClickedRow(row_ix));
665 }
666
667 fn on_cell_right_click(
668 &mut self,
669 _: &MouseDownEvent,
670 row_ix: usize,
671 col_ix: usize,
672 _: &mut Window,
673 cx: &mut Context<Self>,
674 ) {
675 if !self.cell_selectable {
676 return;
677 }
678
679 cx.stop_propagation();
680 self.right_clicked_cell = Some((row_ix, col_ix));
681 self.right_clicked_row = None;
682 cx.emit(TableEvent::RightClickedCell(row_ix, col_ix));
683 }
684
685 fn on_row_left_click(
686 &mut self,
687 e: &ClickEvent,
688 row_ix: usize,
689 _: &mut Window,
690 cx: &mut Context<Self>,
691 ) {
692 if !self.row_selectable {
693 return;
694 }
695
696 self.set_selected_row(row_ix, cx);
697
698 if e.click_count() == 2 {
699 cx.emit(TableEvent::DoubleClickedRow(row_ix));
700 }
701 }
702
703 fn on_col_head_click(&mut self, col_ix: usize, _: &mut Window, cx: &mut Context<Self>) {
704 if !self.col_selectable {
705 return;
706 }
707
708 let Some(col_group) = self.col_groups.get(col_ix) else {
709 return;
710 };
711
712 if !col_group.column.selectable {
713 return;
714 }
715
716 self.set_selected_col(col_ix, cx)
717 }
718
719 fn on_cell_click(
720 &mut self,
721 e: &ClickEvent,
722 row_ix: usize,
723 col_ix: usize,
724 _: &mut Window,
725 cx: &mut Context<Self>,
726 ) {
727 if !self.cell_selectable {
728 return;
729 }
730
731 cx.stop_propagation();
732
733 let is_double_click = e.click_count() == 2;
734
735 let is_reselect =
739 self.selection_mode.is_cell() && self.selected_cell == Some((row_ix, col_ix));
740 let should_escalate_to_row =
741 !self.row_header && self.row_selectable && is_reselect && !is_double_click;
742 if should_escalate_to_row {
743 self.set_selected_row(row_ix, cx);
744 return;
745 }
746
747 self.set_selected_cell(row_ix, col_ix, cx);
748
749 if is_double_click {
750 cx.emit(TableEvent::DoubleClickedCell(row_ix, col_ix));
751 }
752 }
753
754 fn has_selection(&self) -> bool {
755 self.selected_row.is_some() || self.selected_col.is_some() || self.selected_cell.is_some()
756 }
757
758 pub(super) fn action_cancel(&mut self, _: &Cancel, _: &mut Window, cx: &mut Context<Self>) {
759 if self.has_selection() {
760 self.clear_selection(cx);
761 return;
762 }
763 cx.propagate();
764 }
765
766 pub(super) fn action_select_prev(
767 &mut self,
768 _: &SelectUp,
769 _: &mut Window,
770 cx: &mut Context<Self>,
771 ) {
772 let rows_count = self.delegate.rows_count(cx);
773 if rows_count < 1 {
774 return;
775 }
776
777 if self.selection_mode.is_cell() {
779 if let Some((row_ix, col_ix)) = self.selected_cell {
780 let new_row = if row_ix > 0 {
781 row_ix.saturating_sub(1)
782 } else if self.loop_selection {
783 rows_count.saturating_sub(1)
784 } else {
785 row_ix
786 };
787 self.set_selected_cell(new_row, col_ix, cx);
788 } else {
789 self.set_selected_cell(0, 0, cx);
791 }
792 return;
793 }
794
795 let mut selected_row = self.selected_row.unwrap_or(0);
797 if selected_row > 0 {
798 selected_row = selected_row.saturating_sub(1);
799 } else {
800 if self.loop_selection {
801 selected_row = rows_count.saturating_sub(1);
802 }
803 }
804
805 self.set_selected_row(selected_row, cx);
806 }
807
808 pub(super) fn action_select_next(
809 &mut self,
810 _: &SelectDown,
811 _: &mut Window,
812 cx: &mut Context<Self>,
813 ) {
814 let rows_count = self.delegate.rows_count(cx);
815 if rows_count < 1 {
816 return;
817 }
818
819 if self.selection_mode.is_cell() {
821 if let Some((row_ix, col_ix)) = self.selected_cell {
822 let new_row = if row_ix < rows_count.saturating_sub(1) {
823 row_ix + 1
824 } else if self.loop_selection {
825 0
826 } else {
827 row_ix
828 };
829 self.set_selected_cell(new_row, col_ix, cx);
830 } else {
831 self.set_selected_cell(0, 0, cx);
833 }
834 return;
835 }
836
837 let selected_row = match self.selected_row {
839 Some(selected_row) if selected_row < rows_count.saturating_sub(1) => selected_row + 1,
840 Some(selected_row) => {
841 if self.loop_selection {
842 0
843 } else {
844 selected_row
845 }
846 }
847 _ => 0,
848 };
849
850 self.set_selected_row(selected_row, cx);
851 }
852
853 pub(super) fn action_select_first_column(
854 &mut self,
855 _: &SelectFirst,
856 _: &mut Window,
857 cx: &mut Context<Self>,
858 ) {
859 if self.selection_mode.is_cell() {
861 if let Some((row_ix, _)) = self.selected_cell {
862 self.set_selected_cell(row_ix, 0, cx);
863 } else {
864 self.set_selected_cell(0, 0, cx);
866 }
867 return;
868 }
869
870 self.set_selected_col(0, cx);
872 }
873
874 pub(super) fn action_select_last_column(
875 &mut self,
876 _: &SelectLast,
877 _: &mut Window,
878 cx: &mut Context<Self>,
879 ) {
880 let columns_count = self.delegate.columns_count(cx);
881
882 if self.selection_mode.is_cell() {
884 if let Some((row_ix, _)) = self.selected_cell {
885 self.set_selected_cell(row_ix, columns_count.saturating_sub(1), cx);
886 } else {
887 self.set_selected_cell(0, columns_count.saturating_sub(1), cx);
889 }
890 return;
891 }
892
893 self.set_selected_col(columns_count.saturating_sub(1), cx);
895 }
896
897 pub(super) fn action_select_page_up(
898 &mut self,
899 _: &SelectPageUp,
900 _: &mut Window,
901 cx: &mut Context<Self>,
902 ) {
903 let step = self.page_item_count();
904
905 if self.selection_mode.is_cell() {
907 if let Some((row_ix, col_ix)) = self.selected_cell {
908 let target = row_ix.saturating_sub(step);
909 self.set_selected_cell(target, col_ix, cx);
910 } else {
911 self.set_selected_cell(0, 0, cx);
913 }
914 return;
915 }
916
917 let current = self.selected_row.unwrap_or(0);
919 let target = current.saturating_sub(step);
920 self.set_selected_row(target, cx);
921 }
922
923 pub(super) fn action_select_page_down(
924 &mut self,
925 _: &SelectPageDown,
926 _: &mut Window,
927 cx: &mut Context<Self>,
928 ) {
929 let rows_count = self.delegate.rows_count(cx);
930 if rows_count == 0 {
931 return;
932 }
933
934 let step = self.page_item_count();
935
936 if self.selection_mode.is_cell() {
938 if let Some((row_ix, col_ix)) = self.selected_cell {
939 let max_row = rows_count.saturating_sub(1);
940 let target = (row_ix + step).min(max_row);
941 self.set_selected_cell(target, col_ix, cx);
942 } else {
943 self.set_selected_cell(0, 0, cx);
945 }
946 return;
947 }
948
949 let current = self.selected_row.unwrap_or(0);
951 let max_row = rows_count.saturating_sub(1);
952 let target = (current + step).min(max_row);
953 self.set_selected_row(target, cx);
954 }
955
956 pub(super) fn action_select_prev_col(
957 &mut self,
958 _: &SelectPrevColumn,
959 _: &mut Window,
960 cx: &mut Context<Self>,
961 ) {
962 let columns_count = self.delegate.columns_count(cx);
963
964 if self.selection_mode.is_cell() {
966 if let Some((row_ix, col_ix)) = self.selected_cell {
967 let new_col = if col_ix > 0 {
968 col_ix.saturating_sub(1)
969 } else if self.loop_selection {
970 columns_count.saturating_sub(1)
971 } else {
972 col_ix
973 };
974 self.set_selected_cell(row_ix, new_col, cx);
975 } else {
976 self.set_selected_cell(0, 0, cx);
978 }
979 return;
980 }
981
982 let mut selected_col = self.selected_col.unwrap_or(0);
984 if selected_col > 0 {
985 selected_col = selected_col.saturating_sub(1);
986 } else {
987 if self.loop_selection {
988 selected_col = columns_count.saturating_sub(1);
989 }
990 }
991 self.set_selected_col(selected_col, cx);
992 }
993
994 pub(super) fn action_select_next_col(
995 &mut self,
996 _: &SelectNextColumn,
997 _: &mut Window,
998 cx: &mut Context<Self>,
999 ) {
1000 let columns_count = self.delegate.columns_count(cx);
1001
1002 if self.selection_mode.is_cell() {
1004 if let Some((row_ix, col_ix)) = self.selected_cell {
1005 let new_col = if col_ix < columns_count.saturating_sub(1) {
1006 col_ix + 1
1007 } else if self.loop_selection {
1008 0
1009 } else {
1010 col_ix
1011 };
1012 self.set_selected_cell(row_ix, new_col, cx);
1013 } else {
1014 self.set_selected_cell(0, 0, cx);
1016 }
1017 return;
1018 }
1019
1020 let mut selected_col = self.selected_col.unwrap_or(0);
1022 if selected_col < columns_count.saturating_sub(1) {
1023 selected_col += 1;
1024 } else {
1025 if self.loop_selection {
1026 selected_col = 0;
1027 }
1028 }
1029
1030 self.set_selected_col(selected_col, cx);
1031 }
1032
1033 fn scroll_table_by_col_resizing(
1035 &mut self,
1036 mouse_position: Point<Pixels>,
1037 col_group: &ColGroup,
1038 ) {
1039 if mouse_position.x > self.bounds.right() {
1041 return;
1042 }
1043
1044 let mut offset = self.horizontal_scroll_handle.offset();
1045 let col_bounds = col_group.bounds;
1046
1047 if mouse_position.x < self.bounds.left()
1048 && col_bounds.right() < self.bounds.left() + px(20.)
1049 {
1050 offset.x += px(1.);
1051 } else if mouse_position.x > self.bounds.right()
1052 && col_bounds.right() > self.bounds.right() - px(20.)
1053 {
1054 offset.x -= px(1.);
1055 }
1056
1057 self.horizontal_scroll_handle.set_offset(offset);
1058 }
1059
1060 fn resize_cols(&mut self, ix: usize, size: Pixels, _: &mut Window, cx: &mut Context<Self>) {
1063 if !self.col_resizable {
1064 return;
1065 }
1066
1067 let mut changed = false;
1068 if let Some(col_group) = self.col_groups.get_mut(ix) {
1069 if col_group.is_resizable() {
1070 let new_width = size.clamp(col_group.column.min_width, col_group.column.max_width);
1071 if col_group.width != new_width {
1072 col_group.width = new_width;
1073 changed = true;
1074 }
1075 }
1076 }
1077
1078 if changed {
1079 self.update_header_layout(cx);
1080 cx.notify();
1081 }
1082 }
1083
1084 fn perform_sort(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
1085 if !self.sortable {
1086 return;
1087 }
1088
1089 let sort = self.col_groups.get(col_ix).and_then(|g| g.column.sort);
1090 let Some(sort) = sort else {
1092 return;
1093 };
1094 let sort = match sort {
1095 ColumnSort::Ascending => ColumnSort::Default,
1096 ColumnSort::Descending => ColumnSort::Ascending,
1097 ColumnSort::Default => ColumnSort::Descending,
1098 };
1099
1100 for (ix, col_group) in self.col_groups.iter_mut().enumerate() {
1101 if ix == col_ix {
1102 col_group.column.sort = Some(sort);
1103 } else {
1104 if col_group.column.sort.is_some() {
1105 col_group.column.sort = Some(ColumnSort::Default);
1106 }
1107 }
1108 }
1109
1110 self.delegate_mut().perform_sort(col_ix, sort, window, cx);
1111
1112 cx.notify();
1113 }
1114
1115 fn move_column(
1116 &mut self,
1117 col_ix: usize,
1118 to_ix: usize,
1119 window: &mut Window,
1120 cx: &mut Context<Self>,
1121 ) {
1122 if col_ix == to_ix {
1123 return;
1124 }
1125
1126 self.delegate.move_column(col_ix, to_ix, window, cx);
1127 let col_group = self.col_groups.remove(col_ix);
1128 self.col_groups.insert(to_ix, col_group);
1129
1130 cx.emit(TableEvent::MoveColumn(col_ix, to_ix));
1131 cx.notify();
1132 }
1133
1134 fn drag_gap_at(&self, x: Pixels, drag_col_ix: usize) -> Option<usize> {
1137 let fixed_count = self.fixed_left_cols_count();
1138
1139 let candidates = if fixed_count > 0 && x < self.fixed_head_cols_bounds.right() {
1142 0..fixed_count
1143 } else {
1144 self.calculate_visible_leaf_col_range(fixed_count).0
1145 };
1146
1147 let mut gap = candidates.start;
1149 for ix in candidates {
1150 if x < self.col_groups[ix].bounds.center().x {
1151 break;
1152 }
1153 gap = ix + 1;
1154 }
1155
1156 if gap == drag_col_ix || gap == drag_col_ix + 1 {
1158 None
1159 } else {
1160 Some(gap)
1161 }
1162 }
1163
1164 fn load_more_if_need(
1166 &mut self,
1167 rows_count: usize,
1168 visible_end: usize,
1169 window: &mut Window,
1170 cx: &mut Context<Self>,
1171 ) {
1172 let threshold = self.delegate.load_more_threshold();
1173 if visible_end >= rows_count.saturating_sub(threshold) {
1175 if !self.delegate.has_more(cx) {
1176 return;
1177 }
1178
1179 self._load_more_task = cx.spawn_in(window, async move |view, window| {
1180 _ = view.update_in(window, |view, window, cx| {
1181 view.delegate.load_more(window, cx);
1182 });
1183 });
1184 }
1185 }
1186
1187 fn update_visible_range_if_need(
1188 &mut self,
1189 visible_range: Range<usize>,
1190 axis: Axis,
1191 window: &mut Window,
1192 cx: &mut Context<Self>,
1193 ) {
1194 if visible_range.len() <= 1 {
1197 return;
1198 }
1199
1200 if axis == Axis::Vertical {
1201 if self.visible_range.rows == visible_range {
1202 return;
1203 }
1204 self.delegate_mut()
1205 .visible_rows_changed(visible_range.clone(), window, cx);
1206 self.visible_range.rows = visible_range;
1207 } else {
1208 if self.visible_range.cols == visible_range {
1209 return;
1210 }
1211 self.delegate_mut()
1212 .visible_columns_changed(visible_range.clone(), window, cx);
1213 self.visible_range.cols = visible_range;
1214 }
1215 }
1216
1217 fn render_cell(
1218 &self,
1219 _row_ix: Option<usize>,
1220 col_ix: usize,
1221 _window: &mut Window,
1222 _cx: &mut Context<Self>,
1223 ) -> Div {
1224 let Some(col_group) = self.col_groups.get(col_ix) else {
1225 return div();
1226 };
1227
1228 let col_width = col_group.width;
1229 let col_padding = col_group.column.paddings;
1230
1231 div()
1232 .w(col_width)
1233 .h_full()
1234 .flex_shrink_0()
1235 .overflow_hidden()
1236 .whitespace_nowrap()
1237 .table_cell_size(self.options.size)
1238 .map(|this| match col_padding {
1239 Some(padding) => this
1240 .pl(padding.left)
1241 .pr(padding.right)
1242 .pt(padding.top)
1243 .pb(padding.bottom),
1244 None => this,
1245 })
1246 }
1247
1248 fn render_col_wrap(
1251 &self,
1252 _row_ix: Option<usize>,
1253 col_ix: usize,
1254 _: &mut Window,
1255 cx: &mut Context<Self>,
1256 ) -> Div {
1257 let el = h_flex().h_full();
1258 let selectable = self.col_selectable
1259 && self
1260 .col_groups
1261 .get(col_ix)
1262 .map(|col_group| col_group.column.selectable)
1263 .unwrap_or(false);
1264
1265 if self.selection_mode.is_cell() {
1267 return el;
1268 }
1269
1270 if selectable && self.selected_col == Some(col_ix) && self.selection_mode.is_column() {
1271 el.bg(cx.theme().tokens.table_active)
1272 } else {
1273 el
1274 }
1275 }
1276
1277 fn render_resize_handle(
1278 &self,
1279 ix: usize,
1280 _: &mut Window,
1281 cx: &mut Context<Self>,
1282 ) -> impl IntoElement {
1283 const HANDLE_SIZE: Pixels = px(2.);
1284
1285 let resizable = self.col_resizable
1286 && self
1287 .col_groups
1288 .get(ix)
1289 .map(|col| col.is_resizable())
1290 .unwrap_or(false);
1291 if !resizable {
1292 return div().into_any_element();
1293 }
1294
1295 let group_id = SharedString::from(format!("resizable-handle:{}", ix));
1296
1297 h_flex()
1298 .id(("resizable-handle", ix))
1299 .group(group_id.clone())
1300 .occlude()
1301 .cursor_col_resize()
1302 .h_full()
1303 .w(HANDLE_SIZE)
1304 .ml(-(HANDLE_SIZE))
1305 .justify_end()
1306 .items_center()
1307 .child(
1308 div()
1309 .h_full()
1310 .justify_center()
1311 .bg(cx.theme().table_row_border)
1312 .group_hover(&group_id, |this| this.bg(cx.theme().border).h_full())
1313 .w(px(1.)),
1314 )
1315 .on_drag_move(
1316 cx.listener(move |view, e: &DragMoveEvent<ResizeColumn>, window, cx| {
1317 match e.drag(cx) {
1318 ResizeColumn((entity_id, ix)) => {
1319 if cx.entity_id() != *entity_id {
1320 return;
1321 }
1322
1323 let ix = *ix;
1324 view.resizing_col = Some(ix);
1325
1326 let col_group = invariant(
1328 view.col_groups.get(ix),
1329 "表格:命中列索引必在 col_groups 内",
1330 )
1331 .clone();
1332
1333 view.resize_cols(
1334 ix,
1335 e.event.position.x - HANDLE_SIZE - col_group.bounds.left(),
1336 window,
1337 cx,
1338 );
1339
1340 view.scroll_table_by_col_resizing(e.event.position, &col_group);
1342 }
1343 };
1344 }),
1345 )
1346 .on_drag(ResizeColumn((cx.entity_id(), ix)), |drag, _, _, cx| {
1347 cx.stop_propagation();
1348 cx.new(|_| drag.clone())
1349 })
1350 .on_mouse_up_out(
1351 MouseButton::Left,
1352 cx.listener(|view, _, _, cx| {
1353 if view.resizing_col.is_none() {
1354 return;
1355 }
1356
1357 view.resizing_col = None;
1358
1359 let new_widths = view.col_groups.iter().map(|g| g.width).collect();
1360 cx.emit(TableEvent::ColumnWidthsChanged(new_widths));
1361 cx.notify();
1362 }),
1363 )
1364 .into_any_element()
1365 }
1366
1367 fn render_row_header_cell(
1369 &self,
1370 row_ix: usize,
1371 is_head: bool,
1372 cx: &mut Context<Self>,
1373 ) -> impl IntoElement {
1374 div()
1375 .id(("row-header", row_ix))
1376 .w_3()
1377 .h_full()
1378 .border_r_1()
1379 .border_color(cx.theme().table_row_border)
1380 .bg(cx.theme().tokens.table_head)
1381 .flex_shrink_0()
1382 .table_cell_size(self.options.size)
1383 .role(accesskit::Role::RowHeader)
1385 .aria_row_index(row_ix)
1386 .when(!is_head, |this| {
1387 this.when(self.row_selectable, |this| {
1388 this.on_click(cx.listener(move |table, _, _window, cx| {
1389 table.set_selected_row(row_ix, cx);
1390 }))
1391 })
1392 })
1393 }
1394
1395 fn render_sort_icon(
1396 &self,
1397 col_ix: usize,
1398 col_group: &ColGroup,
1399 _: &mut Window,
1400 cx: &mut Context<Self>,
1401 ) -> Option<impl IntoElement> {
1402 if !self.sortable {
1403 return None;
1404 }
1405
1406 let Some(sort) = col_group.column.sort else {
1407 return None;
1408 };
1409
1410 let (icon, is_on) = match sort {
1411 ColumnSort::Ascending => (IconName::SortAscending, true),
1412 ColumnSort::Descending => (IconName::SortDescending, true),
1413 ColumnSort::Default => (IconName::ChevronsUpDown, false),
1414 };
1415
1416 Some(
1417 div()
1418 .id(("icon-sort", col_ix))
1419 .p(px(2.))
1420 .rounded(cx.theme().radius / 2.)
1421 .map(|this| match is_on {
1422 true => this,
1423 false => this.opacity(0.5),
1424 })
1425 .hover(|this| this.bg(cx.theme().tokens.secondary).opacity(7.))
1426 .active(|this| this.bg(cx.theme().tokens.secondary_active).opacity(1.))
1427 .on_click(
1428 cx.listener(move |table, _, window, cx| table.perform_sort(col_ix, window, cx)),
1429 )
1430 .child(
1431 Icon::new(icon)
1432 .size_3()
1433 .text_color(cx.theme().secondary_foreground),
1434 ),
1435 )
1436 }
1437
1438 fn render_th(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) -> Div {
1443 let entity_id = cx.entity_id();
1444 let col_group = invariant(
1446 self.col_groups.get(col_ix),
1447 "表格:表头列索引必在 col_groups 内",
1448 );
1449
1450 let movable = self.col_movable && col_group.column.movable;
1451 let paddings = col_group.column.paddings;
1452 let name = col_group.column.name.clone();
1453
1454 h_flex()
1455 .h_full()
1456 .child(
1457 self.render_cell(None, col_ix, window, cx)
1458 .id(("col-header", col_ix))
1459 .role(accesskit::Role::ColumnHeader)
1461 .aria_column_index(col_ix)
1462 .on_click(cx.listener(move |this, _, window, cx| {
1463 this.on_col_head_click(col_ix, window, cx);
1464 }))
1465 .child(
1466 h_flex()
1467 .size_full()
1468 .justify_between()
1469 .items_center()
1470 .child(self.delegate.render_th(col_ix, window, cx))
1471 .when_some(paddings, |this, paddings| {
1472 let offset_pr =
1474 self.options.size.table_cell_padding().right - paddings.right;
1475 this.pr(offset_pr.max(px(0.)))
1476 })
1477 .children(self.render_sort_icon(col_ix, &col_group, window, cx)),
1478 )
1479 .when(movable, |this| {
1480 this.on_drag(
1481 DragColumn {
1482 entity_id,
1483 col_ix,
1484 name,
1485 width: col_group.width,
1486 },
1487 |drag, _, _, cx| {
1488 cx.stop_propagation();
1489 cx.new(|_| drag.clone())
1490 },
1491 )
1492 })
1493 .map(|this| {
1494 let last_gap = col_ix + 1 == self.col_groups.len();
1497 match self.col_drag_gap {
1498 Some(gap)
1499 if cx.has_active_drag()
1500 && (gap == col_ix || (last_gap && gap == col_ix + 1)) =>
1501 {
1502 let right_side = gap == col_ix + 1;
1503 this.relative().child(
1504 div()
1505 .absolute()
1506 .top_0()
1507 .bottom_0()
1508 .w(px(2.))
1509 .map(|d| if right_side { d.right_0() } else { d.left_0() })
1510 .bg(cx.theme().drag_border),
1511 )
1512 }
1513 _ => this,
1514 }
1515 }),
1516 )
1517 .child(self.render_resize_handle(col_ix, window, cx))
1519 .on_prepaint({
1521 let view = cx.entity();
1522 move |bounds, _, cx| view.update(cx, |r, _| r.col_groups[col_ix].bounds = bounds)
1523 })
1524 }
1525
1526 fn calculate_visible_leaf_col_range(
1536 &self,
1537 left_columns_count: usize,
1538 ) -> (Range<usize>, Pixels) {
1539 let total_cols = self.col_groups.len();
1540
1541 if self.bounds.size.width == px(0.) {
1542 return (left_columns_count..total_cols, px(0.));
1543 }
1544
1545 let fixed_width = self.fixed_head_cols_bounds.size.width;
1546 let available_width = (self.bounds.size.width - fixed_width).max(px(0.));
1547 let scroll_x = (-self.horizontal_scroll_handle.offset().x).max(px(0.));
1549
1550 let mut range_start = left_columns_count;
1553 let mut left_spacer = px(0.);
1554 let mut cumulative = px(0.);
1555 for i in left_columns_count..total_cols {
1556 let right_edge = cumulative + self.col_groups[i].width;
1557 if right_edge > scroll_x {
1558 range_start = i;
1559 left_spacer = cumulative;
1560 break;
1561 }
1562 cumulative = right_edge;
1563 }
1564
1565 let right_bound = scroll_x + available_width + px(200.);
1569 let mut range_end = total_cols;
1570 let mut cumulative = left_spacer; for i in range_start..total_cols {
1572 cumulative += self.col_groups[i].width;
1573 if cumulative > right_bound {
1574 range_end = (i + 1).min(total_cols);
1575 break;
1576 }
1577 }
1578
1579 (range_start..range_end, left_spacer)
1580 }
1581
1582 fn render_table_header(
1583 &mut self,
1584 left_columns_count: usize,
1585 window: &mut Window,
1586 cx: &mut Context<Self>,
1587 ) -> impl IntoElement {
1588 let view = cx.entity();
1589 let horizontal_scroll_handle = self.horizontal_scroll_handle.clone();
1590
1591 let total_cols = self.col_groups.len();
1604 let (visible_col_range, left_spacer) =
1605 self.calculate_visible_leaf_col_range(left_columns_count);
1606
1607 let layout_len = self.header_layout.len();
1608
1609 if left_columns_count == 0 {
1611 self.fixed_head_cols_bounds = Bounds::default();
1612 }
1613
1614 let mut header = self.delegate_mut().render_header(window, cx);
1615 let style = header.style().clone();
1616 let layout = self.header_layout.clone();
1617
1618 header
1619 .h_flex()
1620 .w_full()
1621 .flex_shrink_0()
1622 .bg(cx.theme().tokens.table_head)
1623 .text_color(cx.theme().table_head_foreground)
1624 .refine_style(&style)
1625 .on_drag_move(cx.listener(|table, e: &DragMoveEvent<DragColumn>, _, cx| {
1626 let drag = e.drag(cx);
1627 let (drag_entity_id, drag_col_ix) = (drag.entity_id, drag.col_ix);
1628
1629 let gap =
1630 if drag_entity_id == cx.entity_id() && e.bounds.contains(&e.event.position) {
1631 table.drag_gap_at(e.event.position.x, drag_col_ix)
1632 } else {
1633 None
1634 };
1635
1636 if table.col_drag_gap != gap {
1637 table.col_drag_gap = gap;
1638 cx.notify();
1639 }
1640 }))
1641 .on_drop(cx.listener(|table, drag: &DragColumn, window, cx| {
1642 if drag.entity_id != cx.entity_id() {
1643 return;
1644 }
1645
1646 let Some(gap) = table.col_drag_gap.take() else {
1648 return;
1649 };
1650 let to_ix = if drag.col_ix < gap { gap - 1 } else { gap };
1651 table.move_column(drag.col_ix, to_ix, window, cx);
1652 }))
1653 .when(self.cell_selectable && self.row_header, |this| {
1654 this.child(self.render_row_header_cell(0, true, cx))
1655 })
1656 .when(left_columns_count > 0, |this| {
1657 let view = view.clone();
1658 this.child(
1660 h_flex()
1661 .relative()
1662 .h_full()
1663 .bg(cx.theme().tokens.table_head)
1664 .child(v_flex().min_w_full().flex_shrink_0().children(
1665 layout.iter().enumerate().map(|(_row_ix, row_cells)| {
1666 h_flex()
1667 .min_w_full()
1668 .h(self.options.size.table_row_height())
1669 .border_b_1()
1670 .border_color(cx.theme().border)
1671 .children(row_cells.iter().filter_map(|cell| {
1672 if cell.start_leaf_col_ix < left_columns_count {
1673 if cell.is_leaf {
1674 if let Some(ix) = cell.leaf_col_ix {
1675 return Some(
1676 self.render_th(ix, window, cx)
1677 .into_any_element(),
1678 );
1679 }
1680 } else {
1681 return Some(
1682 self.delegate_mut()
1683 .render_group_th(
1684 &cell.label,
1685 cell.col_span,
1686 cell.width,
1687 window,
1688 cx,
1689 )
1690 .into_any_element(),
1691 );
1692 }
1693 }
1694 None
1695 }))
1696 }),
1697 ))
1698 .child(
1699 div()
1701 .absolute()
1702 .top_0()
1703 .right_0()
1704 .bottom_0()
1705 .w_0()
1706 .flex_shrink_0()
1707 .border_r_1()
1708 .border_color(cx.theme().border),
1709 )
1710 .on_prepaint(move |bounds, _, cx| {
1711 view.update(cx, |r, _| r.fixed_head_cols_bounds = bounds)
1712 }),
1713 )
1714 })
1715 .child(
1716 h_flex()
1718 .id("table-head")
1719 .size_full()
1720 .overflow_scroll()
1721 .relative()
1722 .track_scroll(&horizontal_scroll_handle)
1723 .bg(cx.theme().tokens.table_head)
1724 .child(v_flex().min_w_full().flex_shrink_0().children(
1725 layout.iter().enumerate().map(|(row_ix, row_cells)| {
1726 let is_leaf_row = row_ix + 1 == layout_len;
1727 h_flex()
1728 .min_w_full()
1729 .h(self.options.size.table_row_height())
1730 .border_b_1()
1731 .border_color(cx.theme().border)
1732 .map(|this| {
1733 if is_leaf_row {
1734 this.when(left_spacer > px(0.), |r| {
1739 r.child(div().w(left_spacer).h_full().flex_shrink_0())
1740 })
1741 .children(row_cells.iter().filter_map(|cell| {
1742 if cell.is_leaf {
1743 let ix = cell.leaf_col_ix?;
1744 if !visible_col_range.contains(&ix) {
1745 return None;
1746 }
1747 Some(
1748 self.render_th(ix, window, cx)
1749 .into_any_element(),
1750 )
1751 } else {
1752 None
1753 }
1754 }))
1755 .when(visible_col_range.end < total_cols, |r| {
1756 let right_spacer: Pixels = self.col_groups
1757 [visible_col_range.end..total_cols]
1758 .iter()
1759 .map(|g| g.width)
1760 .sum();
1761 r.child(div().w(right_spacer).h_full().flex_shrink_0())
1762 })
1763 .child(self.delegate.render_last_empty_col(window, cx))
1764 } else {
1765 this.children(row_cells.iter().filter_map(|cell| {
1768 if cell.start_leaf_col_ix >= left_columns_count {
1769 if cell.is_leaf {
1770 if let Some(ix) = cell.leaf_col_ix {
1771 return Some(
1772 self.render_th(ix, window, cx)
1773 .into_any_element(),
1774 );
1775 }
1776 } else {
1777 return Some(
1778 self.delegate_mut()
1779 .render_group_th(
1780 &cell.label,
1781 cell.col_span,
1782 cell.width,
1783 window,
1784 cx,
1785 )
1786 .into_any_element(),
1787 );
1788 }
1789 }
1790 None
1791 }))
1792 .child(self.delegate.render_last_empty_col(window, cx))
1793 }
1794 })
1795 }),
1796 )),
1797 )
1798 }
1799
1800 #[allow(clippy::too_many_arguments)]
1801 fn render_table_row(
1802 &mut self,
1803 row_ix: usize,
1804 rows_count: usize,
1805 left_columns_count: usize,
1806 col_sizes: Rc<Vec<Size<Pixels>>>,
1807 columns_count: usize,
1808 is_filled: bool,
1809 window: &mut Window,
1810 cx: &mut Context<Self>,
1811 ) -> Stateful<Div> {
1812 let horizontal_scroll_handle = self.horizontal_scroll_handle.clone();
1813 let is_stripe_row = self.options.stripe && !row_ix.is_multiple_of(2);
1814 let is_selected = self.selected_row == Some(row_ix);
1815 let view = cx.entity();
1816 let row_height = self.options.size.table_row_height();
1817
1818 if row_ix < rows_count {
1819 let is_last_row = row_ix + 1 == rows_count;
1820 let need_render_border = is_selected || !is_last_row || !is_filled;
1821
1822 let mut tr = self.delegate.render_tr(row_ix, window, cx);
1823 let style = tr.style().clone();
1824
1825 tr.h_flex()
1826 .w_full()
1827 .h(row_height)
1828 .role(accesskit::Role::Row)
1830 .when(need_render_border, |this| {
1831 this.border_b_1().border_color(cx.theme().table_row_border)
1832 })
1833 .when(is_stripe_row, |this| this.bg(cx.theme().tokens.table_even))
1834 .refine_style(&style)
1835 .hover(|this| {
1836 if is_selected || self.right_clicked_row == Some(row_ix) {
1837 this
1838 } else {
1839 this.bg(cx.theme().tokens.table_hover)
1840 }
1841 })
1842 .when(self.cell_selectable && self.row_header, |this| {
1843 this.child(self.render_row_header_cell(row_ix, false, cx))
1844 })
1845 .when(left_columns_count > 0, |this| {
1846 this.child(
1848 h_flex()
1849 .relative()
1850 .h_full()
1851 .children({
1852 let mut items = Vec::with_capacity(left_columns_count);
1853
1854 (0..left_columns_count).for_each(|col_ix| {
1855 let is_cell_selected = self.selected_cell
1856 == Some((row_ix, col_ix))
1857 && self.selection_mode.is_cell();
1858 let is_cell_right_clicked =
1859 self.right_clicked_cell == Some((row_ix, col_ix));
1860
1861 items.push(
1862 self.render_col_wrap(Some(row_ix), col_ix, window, cx)
1863 .child(
1864 self.render_cell(Some(row_ix), col_ix, window, cx)
1865 .id(format!("table-cell:{}:{}", row_ix, col_ix))
1866 .role(accesskit::Role::Cell)
1867 .aria_row_index(row_ix)
1868 .aria_column_index(col_ix)
1869 .relative()
1870 .child(self.measure_render_td(
1871 row_ix, col_ix, window, cx,
1872 ))
1873 .when(is_cell_selected, |this| {
1874 this.child(
1875 div()
1876 .absolute()
1877 .inset_0()
1878 .bg(cx.theme().tokens.table_active)
1879 .border_1()
1880 .border_color(
1881 cx.theme().table_active_border,
1882 ),
1883 )
1884 })
1885 .when(
1886 is_cell_right_clicked && !is_cell_selected,
1887 |this| {
1888 this.child(
1889 div()
1890 .absolute()
1891 .inset_0()
1892 .border_1()
1893 .border_color(
1894 cx.theme()
1895 .table_active_border
1896 .opacity(0.5),
1897 ),
1898 )
1899 },
1900 )
1901 .when(self.cell_selectable, |this| {
1902 this.on_click(cx.listener(
1903 move |table, e, window, cx| {
1904 table.on_cell_click(
1905 e, row_ix, col_ix, window, cx,
1906 );
1907 },
1908 ))
1909 .on_mouse_down(
1910 MouseButton::Right,
1911 cx.listener(
1912 move |table, e, window, cx| {
1913 table.on_cell_right_click(
1914 e, row_ix, col_ix, window,
1915 cx,
1916 );
1917 },
1918 ),
1919 )
1920 }),
1921 ),
1922 );
1923 });
1924
1925 items
1926 })
1927 .child(
1928 div()
1930 .absolute()
1931 .top_0()
1932 .right_0()
1933 .bottom_0()
1934 .w_0()
1935 .flex_shrink_0()
1936 .border_r_1()
1937 .border_color(cx.theme().border),
1938 ),
1939 )
1940 })
1941 .child(
1942 h_flex()
1943 .flex_1()
1944 .h_full()
1945 .overflow_hidden()
1946 .relative()
1947 .child(
1948 crate::h_virtual_list(view, row_ix, col_sizes, {
1949 move |table, visible_range: Range<usize>, window, cx| {
1950 table.update_visible_range_if_need(
1951 visible_range.clone(),
1952 Axis::Horizontal,
1953 window,
1954 cx,
1955 );
1956
1957 let mut items =
1958 Vec::with_capacity(visible_range.end - visible_range.start);
1959
1960 visible_range.for_each(|col_ix| {
1961 let col_ix = col_ix + left_columns_count;
1962 let is_cell_selected = table.selected_cell
1963 == Some((row_ix, col_ix))
1964 && table.selection_mode.is_cell();
1965 let is_cell_right_clicked =
1966 table.right_clicked_cell == Some((row_ix, col_ix));
1967
1968 let el = table
1969 .render_col_wrap(Some(row_ix), col_ix, window, cx)
1970 .child(
1971 table
1972 .render_cell(Some(row_ix), col_ix, window, cx)
1973 .id(format!("table-cell-{}:{}", row_ix, col_ix))
1974 .role(accesskit::Role::Cell)
1975 .aria_row_index(row_ix)
1976 .aria_column_index(col_ix)
1977 .relative()
1978 .child(table.measure_render_td(
1979 row_ix, col_ix, window, cx,
1980 ))
1981 .when(is_cell_selected, |this| {
1982 this.child(
1983 div()
1984 .absolute()
1985 .inset_0()
1986 .bg(cx.theme().tokens.table_active)
1987 .border_1()
1988 .border_color(
1989 cx.theme().table_active_border,
1990 ),
1991 )
1992 })
1993 .when(
1994 is_cell_right_clicked && !is_cell_selected,
1995 |this| {
1996 this.child(
1997 div()
1998 .absolute()
1999 .inset_0()
2000 .border_1()
2001 .border_color(
2002 cx.theme()
2003 .table_active_border
2004 .opacity(0.5),
2005 ),
2006 )
2007 },
2008 )
2009 .when(table.cell_selectable, |this| {
2010 this.on_click(cx.listener(
2011 move |table, e, window, cx| {
2012 cx.stop_propagation();
2013 table.on_cell_click(
2014 e, row_ix, col_ix, window, cx,
2015 );
2016 },
2017 ))
2018 .on_mouse_down(
2019 MouseButton::Right,
2020 cx.listener(
2021 move |table, e, window, cx| {
2022 table.on_cell_right_click(
2023 e, row_ix, col_ix, window,
2024 cx,
2025 );
2026 },
2027 ),
2028 )
2029 }),
2030 );
2031
2032 items.push(el);
2033 });
2034
2035 items
2036 }
2037 })
2038 .with_scroll_handle(&self.horizontal_scroll_handle),
2039 )
2040 .child(self.delegate.render_last_empty_col(window, cx)),
2041 )
2042 .when_some(self.selected_row, |this, _| {
2045 this.when(is_selected && self.selection_mode.is_row(), |this| {
2046 this.map(|this| {
2047 if cx.theme().list.active_highlight {
2048 this.border_color(transparent_white()).child(
2049 div()
2050 .top(if row_ix == 0 { px(0.) } else { px(-1.) })
2051 .left(px(0.))
2052 .right(px(0.))
2053 .bottom(px(-1.))
2054 .absolute()
2055 .bg(cx.theme().tokens.table_active)
2056 .border_1()
2057 .border_color(cx.theme().table_active_border),
2058 )
2059 } else {
2060 this.bg(cx.theme().tokens.accent)
2061 }
2062 })
2063 })
2064 })
2065 .when(self.right_clicked_row == Some(row_ix), |this| {
2067 this.border_color(transparent_white()).child(
2068 div()
2069 .top(if row_ix == 0 { px(0.) } else { px(-1.) })
2070 .left(px(0.))
2071 .right(px(0.))
2072 .bottom(px(-1.))
2073 .absolute()
2074 .border_1()
2075 .border_color(cx.theme().selection),
2076 )
2077 })
2078 .on_mouse_down(
2079 MouseButton::Right,
2080 cx.listener(move |this, e, window, cx| {
2081 this.on_row_right_click(e, Some(row_ix), window, cx);
2082 }),
2083 )
2084 .on_click(cx.listener(move |this, e, window, cx| {
2085 this.on_row_left_click(e, row_ix, window, cx);
2086 }))
2087 } else {
2088 self.delegate
2090 .render_tr(row_ix, window, cx)
2091 .h_flex()
2092 .w_full()
2093 .h(row_height)
2094 .border_b_1()
2095 .border_color(cx.theme().table_row_border)
2096 .when(is_stripe_row, |this| this.bg(cx.theme().tokens.table_even))
2097 .when(self.cell_selectable && self.row_header, |this| {
2098 this.child(
2100 div()
2101 .w(px(40.))
2102 .h_full()
2103 .flex_shrink_0()
2104 .table_cell_size(self.options.size),
2105 )
2106 })
2107 .children((0..columns_count).map(|col_ix| {
2108 h_flex()
2109 .left(horizontal_scroll_handle.offset().x)
2110 .child(self.render_cell(None, col_ix, window, cx))
2111 }))
2112 .child(self.delegate.render_last_empty_col(window, cx))
2113 }
2114 }
2115
2116 fn calculate_extra_rows_needed(
2118 &self,
2119 total_height: Pixels,
2120 actual_height: Pixels,
2121 row_height: Pixels,
2122 ) -> usize {
2123 let mut extra_rows_needed = 0;
2124
2125 let remaining_height = total_height - actual_height;
2126 if remaining_height > px(0.) {
2127 extra_rows_needed = (remaining_height / row_height).floor() as usize;
2128 }
2129
2130 extra_rows_needed
2131 }
2132
2133 #[inline]
2134 fn measure_render_td(
2135 &mut self,
2136 row_ix: usize,
2137 col_ix: usize,
2138 window: &mut Window,
2139 cx: &mut Context<Self>,
2140 ) -> impl IntoElement {
2141 if !measure_enable() {
2142 return self
2143 .delegate
2144 .render_td(row_ix, col_ix, window, cx)
2145 .into_any_element();
2146 }
2147
2148 let start = web_time::Instant::now();
2149 let el = self.delegate.render_td(row_ix, col_ix, window, cx);
2150 self._measure.push(start.elapsed());
2151 el.into_any_element()
2152 }
2153
2154 fn measure(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
2155 if !measure_enable() {
2156 return;
2157 }
2158
2159 if self._measure.len() > 0 {
2161 let total = self
2162 ._measure
2163 .iter()
2164 .fold(Duration::default(), |acc, d| acc + *d);
2165 let avg = total / self._measure.len() as u32;
2166 eprintln!(
2167 "last render {} cells total: {:?}, avg: {:?}",
2168 self._measure.len(),
2169 total,
2170 avg,
2171 );
2172 }
2173 self._measure.clear();
2174 }
2175
2176 fn render_vertical_scrollbar(
2177 &mut self,
2178
2179 _: &mut Window,
2180 _: &mut Context<Self>,
2181 ) -> Option<impl IntoElement> {
2182 let header_rows = self.header_layout.len().max(1);
2183 Some(
2184 div()
2185 .absolute()
2186 .top(self.options.size.table_row_height() * header_rows as f32)
2187 .right_0()
2188 .bottom_0()
2189 .w(Scrollbar::width())
2190 .child(Scrollbar::vertical(&self.vertical_scroll_handle).max_fps(60)),
2191 )
2192 }
2193
2194 fn render_horizontal_scrollbar(
2195 &mut self,
2196 _: &mut Window,
2197 _: &mut Context<Self>,
2198 ) -> impl IntoElement {
2199 div()
2200 .absolute()
2201 .left(self.fixed_head_cols_bounds.size.width)
2202 .right_0()
2203 .bottom_0()
2204 .h(Scrollbar::width())
2205 .child(Scrollbar::horizontal(&self.horizontal_scroll_handle))
2206 }
2207}
2208
2209impl<D> Focusable for TableState<D>
2210where
2211 D: TableDelegate,
2212{
2213 fn focus_handle(&self, _cx: &crate::App) -> FocusHandle {
2214 self.focus_handle.clone()
2215 }
2216}
2217impl<D> EventEmitter<TableEvent> for TableState<D> where D: TableDelegate {}
2218
2219impl<D> Render for TableState<D>
2220where
2221 D: TableDelegate,
2222{
2223 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2224 self.measure(window, cx);
2225
2226 let columns_count = self.delegate.columns_count(cx);
2227 let left_columns_count = self
2228 .col_groups
2229 .iter()
2230 .filter(|col| self.col_fixed && col.column.fixed == Some(ColumnFixed::Left))
2231 .count();
2232 let rows_count = self.delegate.rows_count(cx);
2233 let loading = self.delegate.loading(cx);
2234
2235 let row_height = self.options.size.table_row_height();
2236 let total_height = self
2237 .vertical_scroll_handle
2238 .0
2239 .borrow()
2240 .base_handle
2241 .bounds()
2242 .size
2243 .height;
2244 let actual_height = row_height * rows_count as f32;
2245 let extra_rows_count =
2246 self.calculate_extra_rows_needed(total_height, actual_height, row_height);
2247 let render_rows_count = if self.options.stripe {
2248 rows_count + extra_rows_count
2249 } else {
2250 rows_count
2251 };
2252 let right_clicked_row = self.right_clicked_row;
2253 let is_filled = total_height > Pixels::ZERO && total_height <= actual_height;
2254
2255 let loading_view = if loading {
2256 Some(
2257 self.delegate
2258 .render_loading(self.options.size, window, cx)
2259 .into_any_element(),
2260 )
2261 } else {
2262 None
2263 };
2264
2265 let empty_view = if rows_count == 0 {
2266 Some(
2267 div()
2268 .size_full()
2269 .child(self.delegate.render_empty(window, cx))
2270 .into_any_element(),
2271 )
2272 } else {
2273 None
2274 };
2275
2276 let inner_table = v_flex()
2277 .id("table-inner")
2278 .size_full()
2279 .overflow_hidden()
2280 .child(self.render_table_header(left_columns_count, window, cx))
2281 .context_menu({
2282 let view = cx.entity();
2283 move |this, window: &mut Window, cx: &mut Context<PopupMenu>| {
2284 if let Some(row_ix) = view.read(cx).right_clicked_row {
2285 view.update(cx, |menu, cx| {
2286 menu.delegate_mut().context_menu(row_ix, this, window, cx)
2287 })
2288 } else {
2289 this
2290 }
2291 }
2292 })
2293 .map(|this| {
2294 if rows_count == 0 {
2295 this.children(empty_view)
2296 } else {
2297 this.child(
2298 h_flex().id("table-body").flex_grow_1().size_full().child(
2299 uniform_list(
2300 "table-uniform-list",
2301 render_rows_count,
2302 cx.processor(
2303 move |table, visible_range: Range<usize>, window, cx| {
2304 let col_sizes: Rc<Vec<Size<Pixels>>> = Rc::new(
2308 table
2309 .col_groups
2310 .iter()
2311 .skip(left_columns_count)
2312 .map(|col| Size {
2313 width: col.width,
2314 height: px(0.),
2315 })
2316 .collect(),
2317 );
2318
2319 table.load_more_if_need(
2320 rows_count,
2321 visible_range.end,
2322 window,
2323 cx,
2324 );
2325 table.update_visible_range_if_need(
2326 visible_range.clone(),
2327 Axis::Vertical,
2328 window,
2329 cx,
2330 );
2331
2332 if visible_range.end > rows_count {
2333 table.scroll_to_row(
2334 std::cmp::min(
2335 visible_range.start,
2336 rows_count.saturating_sub(1),
2337 ),
2338 cx,
2339 );
2340 }
2341
2342 let mut items = Vec::with_capacity(
2343 visible_range.end.saturating_sub(visible_range.start),
2344 );
2345
2346 visible_range.for_each(|row_ix| {
2348 items.push(table.render_table_row(
2350 row_ix,
2351 rows_count,
2352 left_columns_count,
2353 col_sizes.clone(),
2354 columns_count,
2355 is_filled,
2356 window,
2357 cx,
2358 ));
2359 });
2360
2361 items
2362 },
2363 ),
2364 )
2365 .flex_grow_1()
2366 .size_full()
2367 .with_sizing_behavior(ListSizingBehavior::Auto)
2368 .track_scroll(&self.vertical_scroll_handle)
2369 .into_any_element(),
2370 ),
2371 )
2372 }
2373 });
2374
2375 div()
2376 .size_full()
2377 .children(loading_view)
2378 .when(!loading, |this| {
2379 this.child(inner_table)
2380 .child(ScrollableMask::new(
2381 Axis::Horizontal,
2382 &self.horizontal_scroll_handle,
2383 ))
2384 .when(rows_count > 0, |this| {
2388 this.child(ScrollableMask::new(
2389 Axis::Vertical,
2390 &self.vertical_scroll_handle.0.borrow().base_handle,
2391 ))
2392 })
2393 .when(right_clicked_row.is_some(), |this| {
2394 this.on_mouse_down_out(cx.listener(|this, e, window, cx| {
2395 this.on_row_right_click(e, None, window, cx);
2396 cx.notify();
2397 }))
2398 })
2399 })
2400 .on_prepaint({
2401 let state = cx.entity();
2402 move |bounds, _, cx| state.update(cx, |state, _| state.bounds = bounds)
2403 })
2404 .when(!window.is_inspector_picking(cx), |this| {
2405 this.child(
2406 div()
2407 .absolute()
2408 .top_0()
2409 .size_full()
2410 .when(self.options.scrollbar_visible.bottom, |this| {
2411 this.child(self.render_horizontal_scrollbar(window, cx))
2412 })
2413 .when(
2414 self.options.scrollbar_visible.right && rows_count > 0,
2415 |this| this.children(self.render_vertical_scrollbar(window, cx)),
2416 ),
2417 )
2418 })
2419 }
2420}