gpui_component/table/state.rs
1use std::{ops::Range, rc::Rc, time::Duration};
2
3use crate::{
4 ActiveTheme, ElementExt, Icon, IconName, StyleSized as _, StyledExt, VirtualListScrollHandle,
5 actions::{
6 Cancel, SelectDown, SelectFirst, SelectLast, SelectNextColumn, SelectPageDown,
7 SelectPageUp, SelectPrevColumn, SelectUp,
8 },
9 h_flex,
10 menu::{ContextMenuExt, PopupMenu},
11 scroll::{ScrollableMask, Scrollbar},
12 v_flex,
13};
14use gpui::ColorExt as _;
15use gpui::{
16 AppContext, Axis, Bounds, ClickEvent, Context, Div, DragMoveEvent, EventEmitter, FocusHandle,
17 Focusable, InteractiveElement, IntoElement, ListSizingBehavior, MouseButton, MouseDownEvent,
18 ParentElement, Pixels, Point, Render, ScrollStrategy, SharedString, Stateful,
19 StatefulInteractiveElement as _, Styled, Task, UniformListScrollHandle, Window, div,
20 prelude::FluentBuilder, px, uniform_list,
21};
22
23use super::*;
24
25#[derive(Copy, Clone, Debug, PartialEq, Eq)]
26enum SelectionMode {
27 Column,
28 Row,
29 Cell,
30}
31
32impl SelectionMode {
33 #[inline(always)]
34 fn is_row(&self) -> bool {
35 matches!(self, SelectionMode::Row)
36 }
37
38 #[inline(always)]
39 fn is_column(&self) -> bool {
40 matches!(self, SelectionMode::Column)
41 }
42
43 #[inline(always)]
44 fn is_cell(&self) -> bool {
45 matches!(self, SelectionMode::Cell)
46 }
47}
48
49/// The Table event.
50#[derive(Clone)]
51pub enum TableEvent {
52 /// Single click or move to selected row.
53 SelectRow(usize),
54 /// Double click on the row.
55 DoubleClickedRow(usize),
56 /// Selected column.
57 SelectColumn(usize),
58 /// A cell has been selected (clicked or navigated to via keyboard).
59 ///
60 /// Emitted when a cell is selected in cell selection mode.
61 /// The first `usize` is the row index, and the second `usize` is the column index.
62 ///
63 /// This event is also emitted when navigating between cells using keyboard shortcuts.
64 SelectCell(usize, usize),
65 /// A cell has been double-clicked.
66 ///
67 /// Emitted when a cell is double-clicked in cell selection mode.
68 /// The first `usize` is the row index, and the second `usize` is the column index.
69 ///
70 /// Use this event to trigger actions like opening a detail view or editing the cell content.
71 DoubleClickedCell(usize, usize),
72 /// The column widths have changed.
73 ///
74 /// The `Vec<Pixels>` contains the new widths of all columns.
75 ColumnWidthsChanged(Vec<Pixels>),
76 /// A column has been moved.
77 ///
78 /// The first `usize` is the original index of the column,
79 /// and the second `usize` is the new index of the column.
80 MoveColumn(usize, usize),
81 /// A row has been right-clicked.
82 ///
83 /// Contains the row index, or `None` if right-clicked on an empty area.
84 /// Use this event to show context menus for rows.
85 RightClickedRow(Option<usize>),
86 /// A cell has been right-clicked.
87 ///
88 /// Emitted when a cell is right-clicked in cell selection mode.
89 /// The first `usize` is the row index, and the second `usize` is the column index.
90 ///
91 /// Use this event to show context menus specific to the cell content.
92 /// The right-clicked cell is highlighted with a subtle border until another cell is clicked.
93 RightClickedCell(usize, usize),
94 /// The selection has been cleared.
95 ///
96 /// This event is emitted when the selection is cleared.
97 ClearSelection,
98}
99
100/// The visible range of the rows and columns.
101#[derive(Debug, Default)]
102pub struct TableVisibleRange {
103 /// The visible range of the rows.
104 rows: Range<usize>,
105 /// The visible range of the columns.
106 cols: Range<usize>,
107}
108
109impl TableVisibleRange {
110 /// Returns the visible range of the rows.
111 pub fn rows(&self) -> &Range<usize> {
112 &self.rows
113 }
114
115 /// Returns the visible range of the columns.
116 pub fn cols(&self) -> &Range<usize> {
117 &self.cols
118 }
119}
120
121/// The state for [`DataTable`].
122///
123/// # Selection Modes
124///
125/// The table supports three selection modes:
126/// - **Row Selection**: Select entire rows (default mode)
127/// - **Column Selection**: Select entire columns
128/// - **Cell Selection**: Select individual cells
129///
130/// ## Cell Selection
131///
132/// When `cell_selectable` is enabled, users can:
133/// - Click on cells to select them
134/// - Right-click on cells to mark them for context menus
135/// - Double-click on cells to trigger actions
136/// - Navigate between cells using keyboard (arrow keys, Home, End, PageUp, PageDown, Tab)
137///
138/// When in cell selection mode, a row header column appears on the left side,
139/// allowing users to select entire rows by clicking on it.
140///
141/// # Events
142///
143/// The table emits the following events related to cell selection:
144/// - [`TableEvent::SelectCell`]: Emitted when a cell is selected
145/// - [`TableEvent::DoubleClickedCell`]: Emitted when a cell is double-clicked
146/// - [`TableEvent::RightClickedCell`]: Emitted when a cell is right-clicked
147///
148/// # Example
149///
150/// ```rust,ignore
151/// let table_state = cx.new(|cx| {
152/// TableState::new(delegate, cx)
153/// .cell_selectable(true)
154/// .row_selectable(true)
155/// });
156///
157/// // Subscribe to cell events
158/// cx.subscribe(&table_state, |this, table, event, cx| {
159/// match event {
160/// TableEvent::SelectCell(row_ix, col_ix) => {
161/// println!("Selected cell: ({}, {})", row_ix, col_ix);
162/// }
163/// TableEvent::DoubleClickedCell(row_ix, col_ix) => {
164/// println!("Double-clicked cell: ({}, {})", row_ix, col_ix);
165/// }
166/// _ => {}
167/// }
168/// });
169/// ```
170#[derive(Clone)]
171pub(crate) struct HeaderCell {
172 pub label: SharedString,
173 pub width: Pixels,
174 col_span: usize,
175 is_leaf: bool,
176 leaf_col_ix: Option<usize>,
177 start_leaf_col_ix: usize,
178}
179
180pub struct TableState<D: TableDelegate> {
181 focus_handle: FocusHandle,
182 delegate: D,
183 pub(super) options: TableOptions,
184 /// The bounds of the table container.
185 bounds: Bounds<Pixels>,
186 /// The bounds of the fixed head cols.
187 fixed_head_cols_bounds: Bounds<Pixels>,
188
189 col_groups: Vec<ColGroup>,
190 header_layout: Vec<Vec<HeaderCell>>,
191
192 /// Whether the table can loop selection, default is true.
193 ///
194 /// When the prev/next selection is out of the table bounds, the selection will loop to the other side.
195 pub loop_selection: bool,
196 /// Whether the table can select column.
197 pub col_selectable: bool,
198 /// Whether the table can select row.
199 pub row_selectable: bool,
200 /// Whether the table can select cell, default is false.
201 ///
202 /// When enabled:
203 /// - Users can click on individual cells to select them
204 /// - A row header column appears on the left for selecting entire rows
205 /// (can be hidden via [`Self::row_header`])
206 /// - Keyboard navigation works at the cell level (arrow keys move between cells)
207 /// - Right-click and double-click events are supported for cells
208 pub cell_selectable: bool,
209 /// Whether the row header column is visible when `cell_selectable` is enabled,
210 /// default is `true`.
211 ///
212 /// Set to `false` to hide the narrow leftmost header column while keeping cell
213 /// selection — useful when you want to put your own content (e.g. a row index
214 /// column) on the left. When hidden, clicking the already-selected cell again
215 /// escalates the selection to the whole row so users can still pick rows; row
216 /// escalation requires `row_selectable` to be enabled.
217 pub row_header: bool,
218 /// Whether the table can sort.
219 pub sortable: bool,
220 /// Whether the table can resize columns.
221 pub col_resizable: bool,
222 /// Whether the table can move columns.
223 pub col_movable: bool,
224 /// Enable/disable fixed columns feature.
225 pub col_fixed: bool,
226
227 pub vertical_scroll_handle: UniformListScrollHandle,
228 pub horizontal_scroll_handle: VirtualListScrollHandle,
229
230 selected_row: Option<usize>,
231 selection_mode: SelectionMode,
232 right_clicked_row: Option<usize>,
233 right_clicked_cell: Option<(usize, usize)>,
234 selected_col: Option<usize>,
235 selected_cell: Option<(usize, usize)>,
236
237 /// The column index that is being resized.
238 resizing_col: Option<usize>,
239
240 /// The insertion gap index (`0..=cols_count`) while dragging a column
241 /// header: the dragged column will be inserted between the columns
242 /// `gap - 1` and `gap` on drop.
243 col_drag_gap: Option<usize>,
244
245 /// The visible range of the rows and columns.
246 visible_range: TableVisibleRange,
247
248 _measure: Vec<Duration>,
249 _load_more_task: Task<()>,
250}
251
252impl<D> TableState<D>
253where
254 D: TableDelegate,
255{
256 /// Create a new TableState with the given delegate.
257 pub fn new(delegate: D, _: &mut Window, cx: &mut Context<Self>) -> Self {
258 let mut this = Self {
259 focus_handle: cx.focus_handle().tab_stop(true),
260 options: TableOptions::default(),
261 delegate,
262 col_groups: Vec::new(),
263 header_layout: Vec::new(),
264 horizontal_scroll_handle: VirtualListScrollHandle::new(),
265 vertical_scroll_handle: UniformListScrollHandle::new(),
266 selection_mode: SelectionMode::Row,
267 selected_row: None,
268 right_clicked_row: None,
269 right_clicked_cell: None,
270 selected_col: None,
271 selected_cell: None,
272 resizing_col: None,
273 col_drag_gap: None,
274 bounds: Bounds::default(),
275 fixed_head_cols_bounds: Bounds::default(),
276 visible_range: TableVisibleRange::default(),
277 loop_selection: true,
278 col_selectable: true,
279 row_selectable: true,
280 cell_selectable: false,
281 row_header: true,
282 sortable: true,
283 col_movable: true,
284 col_resizable: true,
285 col_fixed: true,
286 _load_more_task: Task::ready(()),
287 _measure: Vec::new(),
288 };
289
290 this.prepare_col_groups(cx);
291 this
292 }
293
294 /// Returns a reference to the delegate.
295 pub fn delegate(&self) -> &D {
296 &self.delegate
297 }
298
299 /// Returns a mutable reference to the delegate.
300 pub fn delegate_mut(&mut self) -> &mut D {
301 &mut self.delegate
302 }
303
304 /// Set to loop selection, default to true.
305 pub fn loop_selection(mut self, loop_selection: bool) -> Self {
306 self.loop_selection = loop_selection;
307 self
308 }
309
310 /// Set to enable/disable column movable, default to true.
311 pub fn col_movable(mut self, col_movable: bool) -> Self {
312 self.col_movable = col_movable;
313 self
314 }
315
316 /// Set to enable/disable column resizable, default to true.
317 pub fn col_resizable(mut self, col_resizable: bool) -> Self {
318 self.col_resizable = col_resizable;
319 self
320 }
321
322 /// Set to enable/disable column sortable, default true
323 pub fn sortable(mut self, sortable: bool) -> Self {
324 self.sortable = sortable;
325 self
326 }
327
328 /// Set to enable/disable row selectable, default true
329 pub fn row_selectable(mut self, row_selectable: bool) -> Self {
330 self.row_selectable = row_selectable;
331 self
332 }
333
334 /// Set to enable/disable column selectable, default true
335 pub fn col_selectable(mut self, col_selectable: bool) -> Self {
336 self.col_selectable = col_selectable;
337 self
338 }
339
340 /// Set to enable/disable cell selection, default is false.
341 ///
342 /// When enabled:
343 /// - Individual cells become selectable by clicking
344 /// - A row header column appears on the left side (can be hidden via [`Self::row_header`])
345 /// - Keyboard navigation operates at the cell level
346 /// - Cell-specific events (SelectCell, DoubleClickedCell, RightClickedCell) are emitted
347 ///
348 /// # Example
349 ///
350 /// ```rust,ignore
351 /// let table_state = cx.new(|cx| {
352 /// TableState::new(delegate, cx)
353 /// .cell_selectable(true) // Enable cell selection
354 /// .row_selectable(true) // Also allow row selection via row header
355 /// });
356 /// ```
357 pub fn cell_selectable(mut self, cell_selectable: bool) -> Self {
358 self.cell_selectable = cell_selectable;
359 self
360 }
361
362 /// Set whether the row header column is shown, default is `true`.
363 ///
364 /// Only effective when `cell_selectable` is `true` — otherwise the row header
365 /// column is never rendered. Hide it when you want to use the leftmost column
366 /// for your own content (e.g. a row index column).
367 ///
368 /// When hidden, the first click on a cell selects the cell; clicking the
369 /// already-selected cell again escalates to selecting the whole row, so users
370 /// can still pick rows without the dedicated header column. The row escalation
371 /// requires `row_selectable` to be enabled.
372 pub fn row_header(mut self, row_header: bool) -> Self {
373 self.row_header = row_header;
374 self
375 }
376
377 /// When we update columns or rows, we need to refresh the table.
378 pub fn refresh(&mut self, cx: &mut Context<Self>) {
379 self.prepare_col_groups(cx);
380 }
381
382 /// Scroll to the row at the given index.
383 pub fn scroll_to_row(&mut self, row_ix: usize, cx: &mut Context<Self>) {
384 self.vertical_scroll_handle
385 .scroll_to_item(row_ix, ScrollStrategy::Top);
386 cx.notify();
387 }
388
389 // Scroll to the column at the given index.
390 pub fn scroll_to_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
391 let col_ix = col_ix.saturating_sub(self.fixed_left_cols_count());
392
393 // Resolve the offset here instead of deferring it to the virtual list.
394 //
395 // The header and the rows share `horizontal_scroll_handle`, but only
396 // the rows are a `VirtualList`, and a deferred `scroll_to_item` is
397 // applied during that list's prepaint — which runs *after* the header
398 // has already been rendered and prepainted with the old offset. The
399 // header would therefore stay one frame behind the rows.
400 match self.horizontal_offset_for_col(col_ix) {
401 Some(offset_x) => {
402 let mut offset = self.horizontal_scroll_handle.offset();
403 offset.x = offset_x;
404 self.horizontal_scroll_handle.set_offset(offset);
405 }
406 // Before the first layout the viewport size is unknown, let the
407 // virtual list resolve the offset once it has been laid out.
408 None => self
409 .horizontal_scroll_handle
410 .scroll_to_item(col_ix, ScrollStrategy::Top),
411 }
412
413 cx.notify();
414 }
415
416 /// The horizontal scroll offset that brings the scrollable (non-fixed)
417 /// column at `col_ix` fully into view.
418 ///
419 /// This mirrors the nearest-edge behavior of [`VirtualListScrollHandle::scroll_to_item`]
420 /// with [`ScrollStrategy::Top`]: an already visible column keeps the current
421 /// offset, otherwise the column is aligned to the edge it overflows. Both
422 /// of those move the offset towards a column that exists, so the result
423 /// never runs past the content and needs no extra clamping.
424 ///
425 /// Returns `None` when the viewport size is not known yet, or when `col_ix`
426 /// is out of range.
427 fn horizontal_offset_for_col(&self, col_ix: usize) -> Option<Pixels> {
428 let viewport_width = self.horizontal_scroll_handle.bounds().size.width;
429 if viewport_width <= px(0.) {
430 return None;
431 }
432
433 let cols = self.col_groups.get(self.fixed_left_cols_count()..)?;
434 let col_left: Pixels = cols.get(..col_ix)?.iter().map(|col| col.width).sum();
435 let col_right = col_left + cols.get(col_ix)?.width;
436 let offset_x = self.horizontal_scroll_handle.offset().x;
437
438 Some(if col_left + offset_x < px(0.) {
439 -col_left
440 } else if col_right + offset_x > viewport_width {
441 viewport_width - col_right
442 } else {
443 offset_x
444 })
445 }
446
447 /// Returns the selected row index.
448 pub fn selected_row(&self) -> Option<usize> {
449 self.selected_row
450 }
451
452 /// Sets the selected row to the given index.
453 pub fn set_selected_row(&mut self, row_ix: usize, cx: &mut Context<Self>) {
454 let is_down = match self.selected_row {
455 Some(selected_row) => row_ix > selected_row,
456 None => true,
457 };
458
459 cx.stop_propagation();
460 self.selection_mode = SelectionMode::Row;
461 self.right_clicked_row = None;
462 self.selected_row = Some(row_ix);
463 if let Some(row_ix) = self.selected_row {
464 self.vertical_scroll_handle.scroll_to_item(
465 row_ix,
466 if is_down {
467 ScrollStrategy::Bottom
468 } else {
469 ScrollStrategy::Top
470 },
471 );
472 }
473 cx.emit(TableEvent::SelectRow(row_ix));
474 cx.emit(TableEvent::RightClickedRow(None));
475 cx.notify();
476 }
477
478 /// Returns the row that has been right clicked.
479 pub fn right_clicked_row(&self) -> Option<usize> {
480 self.right_clicked_row
481 }
482
483 /// Set or clear the right-clicked row state.
484 ///
485 /// Pass `None` to clear — useful when opening a header context menu
486 /// to prevent the row context menu from appearing simultaneously.
487 pub fn set_right_clicked_row(&mut self, row: Option<usize>, cx: &mut Context<Self>) {
488 self.right_clicked_row = row;
489 cx.notify();
490 }
491
492 /// Returns the selected column index.
493 pub fn selected_col(&self) -> Option<usize> {
494 self.selected_col
495 }
496
497 /// Sets the selected col to the given index.
498 pub fn set_selected_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
499 self.selection_mode = SelectionMode::Column;
500 self.selected_col = Some(col_ix);
501 if let Some(col_ix) = self.selected_col {
502 self.scroll_to_col(col_ix, cx);
503 }
504 cx.emit(TableEvent::SelectColumn(col_ix));
505 cx.notify();
506 }
507
508 /// Returns the selected cell as `(row_ix, col_ix)`.
509 ///
510 /// Returns `None` if no cell is currently selected or if the table is in row/column selection mode.
511 ///
512 /// # Example
513 ///
514 /// ```rust,ignore
515 /// if let Some((row_ix, col_ix)) = table_state.read(cx).selected_cell() {
516 /// println!("Selected cell: ({}, {})", row_ix, col_ix);
517 /// }
518 /// ```
519 pub fn selected_cell(&self) -> Option<(usize, usize)> {
520 self.selected_cell
521 }
522
523 /// Sets the selected cell to the given row and column indices.
524 ///
525 /// This method:
526 /// - Switches the table to cell selection mode
527 /// - Scrolls to make the cell visible (centered vertically)
528 /// - Emits a [`TableEvent::SelectCell`] event
529 ///
530 /// # Example
531 ///
532 /// ```rust,ignore
533 /// // Select the cell at row 5, column 3
534 /// table_state.update(cx, |state, cx| {
535 /// state.set_selected_cell(5, 3, cx);
536 /// });
537 /// ```
538 pub fn set_selected_cell(&mut self, row_ix: usize, col_ix: usize, cx: &mut Context<Self>) {
539 self.selection_mode = SelectionMode::Cell;
540 self.selected_cell = Some((row_ix, col_ix));
541
542 // Scroll to the cell
543 self.vertical_scroll_handle
544 .scroll_to_item(row_ix, ScrollStrategy::Center);
545 self.scroll_to_col(col_ix, cx);
546
547 cx.emit(TableEvent::SelectCell(row_ix, col_ix));
548 cx.notify();
549 }
550
551 /// Clear the selection of the table.
552 pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
553 self.selection_mode = SelectionMode::Row;
554 self.selected_row = None;
555 self.selected_col = None;
556 self.selected_cell = None;
557 cx.emit(TableEvent::ClearSelection);
558 cx.notify();
559 }
560
561 /// Returns the visible range of the rows and columns.
562 ///
563 /// See [`TableVisibleRange`].
564 pub fn visible_range(&self) -> &TableVisibleRange {
565 &self.visible_range
566 }
567
568 /// Dump the header row of the table.
569 ///
570 /// Batched exporters can read the headers once with this, then stream the
571 /// rows with [`Self::dump_range`].
572 pub fn headers(&self, cx: &App) -> Vec<String> {
573 let columns_count = self.delegate.columns_count(cx);
574 let mut headers = Vec::with_capacity(columns_count);
575 for col_ix in 0..columns_count {
576 let column = self.delegate.column(col_ix, cx);
577 headers.push(column.name.to_string());
578 }
579
580 headers
581 }
582
583 /// Dump table data.
584 ///
585 /// Returns a tuple of (headers, rows) where each row is a vector of cell values.
586 ///
587 /// This materializes the complete table in memory. For large tables, prefer
588 /// [`Self::dump_range`] and process rows in batches.
589 pub fn dump(&self, cx: &App) -> (Vec<String>, Vec<Vec<String>>) {
590 self.dump_range(0..self.delegate.rows_count(cx), cx)
591 }
592
593 /// Dump table data for the specified row range.
594 ///
595 /// Returns the same `(headers, rows)` shape as [`Self::dump`], with only
596 /// the rows inside the clamped range.
597 ///
598 /// The requested range is clamped to the table's current row count. For
599 /// large tables, callers can invoke this repeatedly with bounded ranges.
600 pub fn dump_range(&self, range: Range<usize>, cx: &App) -> (Vec<String>, Vec<Vec<String>>) {
601 let columns_count = self.delegate.columns_count(cx);
602 let rows_count = self.delegate.rows_count(cx);
603 let start = range.start.min(rows_count);
604 let end = range.end.min(rows_count).max(start);
605
606 let mut rows = Vec::with_capacity(end - start);
607 for row_ix in start..end {
608 let mut row = Vec::with_capacity(columns_count);
609 for col_ix in 0..columns_count {
610 row.push(self.delegate.cell_text(row_ix, col_ix, cx));
611 }
612 rows.push(row);
613 }
614
615 (self.headers(cx), rows)
616 }
617
618 /// Re-compute the header layout from the current delegate.
619 ///
620 /// Call this after changing delegate state that affects `group_headers`.
621 pub fn refresh_header_layout(&mut self, cx: &mut Context<Self>) {
622 self.update_header_layout(cx);
623 cx.notify();
624 }
625
626 fn prepare_col_groups(&mut self, cx: &mut Context<Self>) {
627 self.col_groups = (0..self.delegate.columns_count(cx))
628 .map(|col_ix| {
629 let column = self.delegate().column(col_ix, cx);
630 ColGroup {
631 width: column.width,
632 bounds: Bounds::default(),
633 column,
634 }
635 })
636 .collect();
637
638 self.update_header_layout(cx);
639 }
640
641 fn update_header_layout(&mut self, cx: &mut Context<Self>) {
642 let group_rows = self.delegate.group_headers(cx);
643
644 let mut layout = match group_rows.as_ref() {
645 Some(rows) => Vec::with_capacity(rows.len() + 1),
646 None => Vec::with_capacity(1),
647 };
648
649 if let Some(group_rows) = group_rows {
650 for row in group_rows {
651 let mut cell_row = Vec::with_capacity(row.len());
652 let mut current_leaf_ix = 0;
653 for group in row {
654 let mut width = px(0.);
655 let start_leaf_col_ix = current_leaf_ix;
656 for i in 0..group.span {
657 if current_leaf_ix + i < self.col_groups.len() {
658 width += self.col_groups[current_leaf_ix + i].width;
659 }
660 }
661 current_leaf_ix += group.span;
662 cell_row.push(HeaderCell {
663 label: group.label.clone(),
664 width,
665 col_span: group.span,
666 is_leaf: false,
667 leaf_col_ix: None,
668 start_leaf_col_ix,
669 });
670 }
671 layout.push(cell_row);
672 }
673 }
674
675 let mut leaf_row = Vec::with_capacity(self.col_groups.len());
676 for (ix, group) in self.col_groups.iter().enumerate() {
677 leaf_row.push(HeaderCell {
678 label: group.column.name.clone(),
679 width: group.width,
680 col_span: 1,
681 is_leaf: true,
682 leaf_col_ix: Some(ix),
683 start_leaf_col_ix: ix,
684 });
685 }
686 layout.push(leaf_row);
687
688 self.header_layout = layout;
689 }
690
691 fn fixed_left_cols_count(&self) -> usize {
692 if !self.col_fixed {
693 return 0;
694 }
695
696 self.col_groups
697 .iter()
698 .filter(|col| col.column.fixed == Some(ColumnFixed::Left))
699 .count()
700 }
701
702 fn page_item_count(&self) -> usize {
703 let row_height = self.options.size.table_row_height();
704 let height = self.bounds.size.height;
705 let count = (height / row_height).floor() as usize;
706 count.saturating_sub(1).max(1)
707 }
708
709 fn on_row_right_click(
710 &mut self,
711 _: &MouseDownEvent,
712 row_ix: Option<usize>,
713 _: &mut Window,
714 cx: &mut Context<Self>,
715 ) {
716 self.right_clicked_row = row_ix;
717 self.right_clicked_cell = None;
718 cx.emit(TableEvent::RightClickedRow(row_ix));
719 }
720
721 fn on_cell_right_click(
722 &mut self,
723 _: &MouseDownEvent,
724 row_ix: usize,
725 col_ix: usize,
726 _: &mut Window,
727 cx: &mut Context<Self>,
728 ) {
729 if !self.cell_selectable {
730 return;
731 }
732
733 cx.stop_propagation();
734 self.right_clicked_cell = Some((row_ix, col_ix));
735 self.right_clicked_row = None;
736 cx.emit(TableEvent::RightClickedCell(row_ix, col_ix));
737 }
738
739 fn on_row_left_click(
740 &mut self,
741 e: &ClickEvent,
742 row_ix: usize,
743 _: &mut Window,
744 cx: &mut Context<Self>,
745 ) {
746 if !self.row_selectable {
747 return;
748 }
749
750 self.set_selected_row(row_ix, cx);
751
752 if e.click_count() == 2 {
753 cx.emit(TableEvent::DoubleClickedRow(row_ix));
754 }
755 }
756
757 fn on_col_head_click(&mut self, col_ix: usize, _: &mut Window, cx: &mut Context<Self>) {
758 if !self.col_selectable {
759 return;
760 }
761
762 let Some(col_group) = self.col_groups.get(col_ix) else {
763 return;
764 };
765
766 if !col_group.column.selectable {
767 return;
768 }
769
770 self.set_selected_col(col_ix, cx)
771 }
772
773 fn on_cell_click(
774 &mut self,
775 e: &ClickEvent,
776 row_ix: usize,
777 col_ix: usize,
778 _: &mut Window,
779 cx: &mut Context<Self>,
780 ) {
781 if !self.cell_selectable {
782 return;
783 }
784
785 cx.stop_propagation();
786
787 let is_double_click = e.click_count() == 2;
788
789 // When the row header column is hidden, a single click on the
790 // already-selected cell escalates the selection to the entire row —
791 // giving users a way to pick rows without the dedicated header column.
792 // Double-clicks are passed through to `DoubleClickedCell` and never
793 // trigger the escalation.
794 let is_reselect =
795 self.selection_mode.is_cell() && self.selected_cell == Some((row_ix, col_ix));
796 let should_escalate_to_row =
797 !self.row_header && self.row_selectable && is_reselect && !is_double_click;
798 if should_escalate_to_row {
799 self.set_selected_row(row_ix, cx);
800 return;
801 }
802
803 self.set_selected_cell(row_ix, col_ix, cx);
804
805 if is_double_click {
806 cx.emit(TableEvent::DoubleClickedCell(row_ix, col_ix));
807 }
808 }
809
810 fn has_selection(&self) -> bool {
811 self.selected_row.is_some() || self.selected_col.is_some() || self.selected_cell.is_some()
812 }
813
814 pub(super) fn action_cancel(&mut self, _: &Cancel, _: &mut Window, cx: &mut Context<Self>) {
815 if self.has_selection() {
816 self.clear_selection(cx);
817 return;
818 }
819 cx.propagate();
820 }
821
822 pub(super) fn action_select_prev(
823 &mut self,
824 _: &SelectUp,
825 _: &mut Window,
826 cx: &mut Context<Self>,
827 ) {
828 let rows_count = self.delegate.rows_count(cx);
829 if rows_count < 1 {
830 return;
831 }
832
833 // Cell selection mode: move up within the same column
834 if self.selection_mode.is_cell() {
835 if let Some((row_ix, col_ix)) = self.selected_cell {
836 let new_row = if row_ix > 0 {
837 row_ix.saturating_sub(1)
838 } else if self.loop_selection {
839 rows_count.saturating_sub(1)
840 } else {
841 row_ix
842 };
843 self.set_selected_cell(new_row, col_ix, cx);
844 } else {
845 // No cell selected, select first cell
846 self.set_selected_cell(0, 0, cx);
847 }
848 return;
849 }
850
851 // Row selection mode
852 let mut selected_row = self.selected_row.unwrap_or(0);
853 if selected_row > 0 {
854 selected_row = selected_row.saturating_sub(1);
855 } else {
856 if self.loop_selection {
857 selected_row = rows_count.saturating_sub(1);
858 }
859 }
860
861 self.set_selected_row(selected_row, cx);
862 }
863
864 pub(super) fn action_select_next(
865 &mut self,
866 _: &SelectDown,
867 _: &mut Window,
868 cx: &mut Context<Self>,
869 ) {
870 let rows_count = self.delegate.rows_count(cx);
871 if rows_count < 1 {
872 return;
873 }
874
875 // Cell selection mode: move down within the same column
876 if self.selection_mode.is_cell() {
877 if let Some((row_ix, col_ix)) = self.selected_cell {
878 let new_row = if row_ix < rows_count.saturating_sub(1) {
879 row_ix + 1
880 } else if self.loop_selection {
881 0
882 } else {
883 row_ix
884 };
885 self.set_selected_cell(new_row, col_ix, cx);
886 } else {
887 // No cell selected, select first cell
888 self.set_selected_cell(0, 0, cx);
889 }
890 return;
891 }
892
893 // Row selection mode
894 let selected_row = match self.selected_row {
895 Some(selected_row) if selected_row < rows_count.saturating_sub(1) => selected_row + 1,
896 Some(selected_row) => {
897 if self.loop_selection {
898 0
899 } else {
900 selected_row
901 }
902 }
903 _ => 0,
904 };
905
906 self.set_selected_row(selected_row, cx);
907 }
908
909 pub(super) fn action_select_first_column(
910 &mut self,
911 _: &SelectFirst,
912 _: &mut Window,
913 cx: &mut Context<Self>,
914 ) {
915 // Cell selection mode: move to first cell in current row
916 if self.selection_mode.is_cell() {
917 if let Some((row_ix, _)) = self.selected_cell {
918 self.set_selected_cell(row_ix, 0, cx);
919 } else {
920 // No cell selected, select first cell of first row
921 self.set_selected_cell(0, 0, cx);
922 }
923 return;
924 }
925
926 // Column selection mode
927 self.set_selected_col(0, cx);
928 }
929
930 pub(super) fn action_select_last_column(
931 &mut self,
932 _: &SelectLast,
933 _: &mut Window,
934 cx: &mut Context<Self>,
935 ) {
936 let columns_count = self.delegate.columns_count(cx);
937
938 // Cell selection mode: move to last cell in current row
939 if self.selection_mode.is_cell() {
940 if let Some((row_ix, _)) = self.selected_cell {
941 self.set_selected_cell(row_ix, columns_count.saturating_sub(1), cx);
942 } else {
943 // No cell selected, select last cell of first row
944 self.set_selected_cell(0, columns_count.saturating_sub(1), cx);
945 }
946 return;
947 }
948
949 // Column selection mode
950 self.set_selected_col(columns_count.saturating_sub(1), cx);
951 }
952
953 pub(super) fn action_select_page_up(
954 &mut self,
955 _: &SelectPageUp,
956 _: &mut Window,
957 cx: &mut Context<Self>,
958 ) {
959 let step = self.page_item_count();
960
961 // Cell selection mode: move up by page within the same column
962 if self.selection_mode.is_cell() {
963 if let Some((row_ix, col_ix)) = self.selected_cell {
964 let target = row_ix.saturating_sub(step);
965 self.set_selected_cell(target, col_ix, cx);
966 } else {
967 // No cell selected, select first cell
968 self.set_selected_cell(0, 0, cx);
969 }
970 return;
971 }
972
973 // Row selection mode
974 let current = self.selected_row.unwrap_or(0);
975 let target = current.saturating_sub(step);
976 self.set_selected_row(target, cx);
977 }
978
979 pub(super) fn action_select_page_down(
980 &mut self,
981 _: &SelectPageDown,
982 _: &mut Window,
983 cx: &mut Context<Self>,
984 ) {
985 let rows_count = self.delegate.rows_count(cx);
986 if rows_count == 0 {
987 return;
988 }
989
990 let step = self.page_item_count();
991
992 // Cell selection mode: move down by page within the same column
993 if self.selection_mode.is_cell() {
994 if let Some((row_ix, col_ix)) = self.selected_cell {
995 let max_row = rows_count.saturating_sub(1);
996 let target = (row_ix + step).min(max_row);
997 self.set_selected_cell(target, col_ix, cx);
998 } else {
999 // No cell selected, select first cell
1000 self.set_selected_cell(0, 0, cx);
1001 }
1002 return;
1003 }
1004
1005 // Row selection mode
1006 let current = self.selected_row.unwrap_or(0);
1007 let max_row = rows_count.saturating_sub(1);
1008 let target = (current + step).min(max_row);
1009 self.set_selected_row(target, cx);
1010 }
1011
1012 pub(super) fn action_select_prev_col(
1013 &mut self,
1014 _: &SelectPrevColumn,
1015 _: &mut Window,
1016 cx: &mut Context<Self>,
1017 ) {
1018 let columns_count = self.delegate.columns_count(cx);
1019
1020 // Cell selection mode: move left within the same row
1021 if self.selection_mode.is_cell() {
1022 if let Some((row_ix, col_ix)) = self.selected_cell {
1023 let new_col = if col_ix > 0 {
1024 col_ix.saturating_sub(1)
1025 } else if self.loop_selection {
1026 columns_count.saturating_sub(1)
1027 } else {
1028 col_ix
1029 };
1030 self.set_selected_cell(row_ix, new_col, cx);
1031 } else {
1032 // No cell selected, select first cell
1033 self.set_selected_cell(0, 0, cx);
1034 }
1035 return;
1036 }
1037
1038 // Column selection mode
1039 let mut selected_col = self.selected_col.unwrap_or(0);
1040 if selected_col > 0 {
1041 selected_col = selected_col.saturating_sub(1);
1042 } else {
1043 if self.loop_selection {
1044 selected_col = columns_count.saturating_sub(1);
1045 }
1046 }
1047 self.set_selected_col(selected_col, cx);
1048 }
1049
1050 pub(super) fn action_select_next_col(
1051 &mut self,
1052 _: &SelectNextColumn,
1053 _: &mut Window,
1054 cx: &mut Context<Self>,
1055 ) {
1056 let columns_count = self.delegate.columns_count(cx);
1057
1058 // Cell selection mode: move right within the same row
1059 if self.selection_mode.is_cell() {
1060 if let Some((row_ix, col_ix)) = self.selected_cell {
1061 let new_col = if col_ix < columns_count.saturating_sub(1) {
1062 col_ix + 1
1063 } else if self.loop_selection {
1064 0
1065 } else {
1066 col_ix
1067 };
1068 self.set_selected_cell(row_ix, new_col, cx);
1069 } else {
1070 // No cell selected, select first cell
1071 self.set_selected_cell(0, 0, cx);
1072 }
1073 return;
1074 }
1075
1076 // Column selection mode
1077 let mut selected_col = self.selected_col.unwrap_or(0);
1078 if selected_col < columns_count.saturating_sub(1) {
1079 selected_col += 1;
1080 } else {
1081 if self.loop_selection {
1082 selected_col = 0;
1083 }
1084 }
1085
1086 self.set_selected_col(selected_col, cx);
1087 }
1088
1089 /// Scroll table when mouse position is near the edge of the table bounds.
1090 fn scroll_table_by_col_resizing(
1091 &mut self,
1092 mouse_position: Point<Pixels>,
1093 col_group: &ColGroup,
1094 ) {
1095 // Do nothing if pos out of the table bounds right for avoid scroll to the right.
1096 if mouse_position.x > self.bounds.right() {
1097 return;
1098 }
1099
1100 let mut offset = self.horizontal_scroll_handle.offset();
1101 let col_bounds = col_group.bounds;
1102
1103 if mouse_position.x < self.bounds.left()
1104 && col_bounds.right() < self.bounds.left() + px(20.)
1105 {
1106 offset.x += px(1.);
1107 } else if mouse_position.x > self.bounds.right()
1108 && col_bounds.right() > self.bounds.right() - px(20.)
1109 {
1110 offset.x -= px(1.);
1111 }
1112
1113 self.horizontal_scroll_handle.set_offset(offset);
1114 }
1115
1116 /// The `ix`` is the index of the col to resize,
1117 /// and the `size` is the new size for the col.
1118 fn resize_cols(&mut self, ix: usize, size: Pixels, _: &mut Window, cx: &mut Context<Self>) {
1119 if !self.col_resizable {
1120 return;
1121 }
1122
1123 let mut changed = false;
1124 if let Some(col_group) = self.col_groups.get_mut(ix) {
1125 if col_group.is_resizable() {
1126 let new_width = size.clamp(col_group.column.min_width, col_group.column.max_width);
1127 if col_group.width != new_width {
1128 col_group.width = new_width;
1129 changed = true;
1130 }
1131 }
1132 }
1133
1134 if changed {
1135 self.update_header_layout(cx);
1136 cx.notify();
1137 }
1138 }
1139
1140 fn perform_sort(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
1141 if !self.sortable {
1142 return;
1143 }
1144
1145 let sort = self.col_groups.get(col_ix).and_then(|g| g.column.sort);
1146 if sort.is_none() {
1147 return;
1148 }
1149
1150 let sort = sort.unwrap();
1151 let sort = match sort {
1152 ColumnSort::Ascending => ColumnSort::Default,
1153 ColumnSort::Descending => ColumnSort::Ascending,
1154 ColumnSort::Default => ColumnSort::Descending,
1155 };
1156
1157 for (ix, col_group) in self.col_groups.iter_mut().enumerate() {
1158 if ix == col_ix {
1159 col_group.column.sort = Some(sort);
1160 } else {
1161 if col_group.column.sort.is_some() {
1162 col_group.column.sort = Some(ColumnSort::Default);
1163 }
1164 }
1165 }
1166
1167 self.delegate_mut().perform_sort(col_ix, sort, window, cx);
1168
1169 cx.notify();
1170 }
1171
1172 fn move_column(
1173 &mut self,
1174 col_ix: usize,
1175 to_ix: usize,
1176 window: &mut Window,
1177 cx: &mut Context<Self>,
1178 ) {
1179 if col_ix == to_ix {
1180 return;
1181 }
1182
1183 self.delegate.move_column(col_ix, to_ix, window, cx);
1184 let col_group = self.col_groups.remove(col_ix);
1185 self.col_groups.insert(to_ix, col_group);
1186
1187 cx.emit(TableEvent::MoveColumn(col_ix, to_ix));
1188 cx.notify();
1189 }
1190
1191 /// Resolve the insertion gap for a column-header drag at the window
1192 /// coordinate `x`, or `None` when dropping there would not move the
1193 /// dragged column at `drag_col_ix`.
1194 fn drag_gap_at(&self, x: Pixels, drag_col_ix: usize) -> Option<usize> {
1195 let fixed_count = self.fixed_left_cols_count();
1196
1197 // Columns scrolled beneath the fixed region keep stale bounds, so
1198 // resolve `x` against the fixed columns alone when it falls in that
1199 // region, and against the visible scrollable columns otherwise.
1200 let candidates = if fixed_count > 0 && x < self.fixed_head_cols_bounds.right() {
1201 0..fixed_count
1202 } else {
1203 self.calculate_visible_leaf_col_range(fixed_count).0
1204 };
1205
1206 // The gap sits after the last candidate column whose center is left of `x`.
1207 let mut gap = candidates.start;
1208 for ix in candidates {
1209 if x < self.col_groups[ix].bounds.center().x {
1210 break;
1211 }
1212 gap = ix + 1;
1213 }
1214
1215 // No gap if dropping there would put the dragged column back to
1216 // where it already is.
1217 if gap == drag_col_ix || gap == drag_col_ix + 1 {
1218 None
1219 } else {
1220 Some(gap)
1221 }
1222 }
1223
1224 /// Dispatch delegate's `load_more` method when the visible range is near the end.
1225 fn load_more_if_need(
1226 &mut self,
1227 rows_count: usize,
1228 visible_end: usize,
1229 window: &mut Window,
1230 cx: &mut Context<Self>,
1231 ) {
1232 let threshold = self.delegate.load_more_threshold();
1233 // Securely handle subtract logic to prevent attempt to subtract with overflow
1234 if visible_end >= rows_count.saturating_sub(threshold) {
1235 if !self.delegate.has_more(cx) {
1236 return;
1237 }
1238
1239 self._load_more_task = cx.spawn_in(window, async move |view, window| {
1240 _ = view.update_in(window, |view, window, cx| {
1241 view.delegate.load_more(window, cx);
1242 });
1243 });
1244 }
1245 }
1246
1247 fn update_visible_range_if_need(
1248 &mut self,
1249 visible_range: Range<usize>,
1250 axis: Axis,
1251 window: &mut Window,
1252 cx: &mut Context<Self>,
1253 ) {
1254 // Skip when visible range is only 1 item.
1255 // The visual_list will use first item to measure.
1256 if visible_range.len() <= 1 {
1257 return;
1258 }
1259
1260 if axis == Axis::Vertical {
1261 if self.visible_range.rows == visible_range {
1262 return;
1263 }
1264 self.delegate_mut()
1265 .visible_rows_changed(visible_range.clone(), window, cx);
1266 self.visible_range.rows = visible_range;
1267 } else {
1268 if self.visible_range.cols == visible_range {
1269 return;
1270 }
1271 self.delegate_mut()
1272 .visible_columns_changed(visible_range.clone(), window, cx);
1273 self.visible_range.cols = visible_range;
1274 }
1275 }
1276
1277 fn render_cell(
1278 &self,
1279 _row_ix: Option<usize>,
1280 col_ix: usize,
1281 _window: &mut Window,
1282 _cx: &mut Context<Self>,
1283 ) -> Div {
1284 let Some(col_group) = self.col_groups.get(col_ix) else {
1285 return div();
1286 };
1287
1288 let col_width = col_group.width;
1289 let col_padding = col_group.column.paddings;
1290
1291 div()
1292 .w(col_width)
1293 .h_full()
1294 .flex_shrink_0()
1295 .overflow_hidden()
1296 .whitespace_nowrap()
1297 .table_cell_size(self.options.size)
1298 .map(|this| match col_padding {
1299 Some(padding) => this
1300 .pl(padding.left)
1301 .pr(padding.right)
1302 .pt(padding.top)
1303 .pb(padding.bottom),
1304 None => this,
1305 })
1306 }
1307
1308 /// Show Column selection style, when the column is selected and the selection state is Column.
1309 /// Note: When a cell is selected, column selection style is not shown.
1310 fn render_col_wrap(
1311 &self,
1312 _row_ix: Option<usize>,
1313 col_ix: usize,
1314 _: &mut Window,
1315 cx: &mut Context<Self>,
1316 ) -> Div {
1317 let el = h_flex().h_full();
1318 let selectable = self.col_selectable
1319 && self
1320 .col_groups
1321 .get(col_ix)
1322 .map(|col_group| col_group.column.selectable)
1323 .unwrap_or(false);
1324
1325 // Don't show column selection if a cell is selected
1326 if self.selection_mode.is_cell() {
1327 return el;
1328 }
1329
1330 if selectable && self.selected_col == Some(col_ix) && self.selection_mode.is_column() {
1331 el.bg(cx.theme().tokens.table_active)
1332 } else {
1333 el
1334 }
1335 }
1336
1337 fn render_resize_handle(
1338 &self,
1339 ix: usize,
1340 _: &mut Window,
1341 cx: &mut Context<Self>,
1342 ) -> impl IntoElement {
1343 const HANDLE_SIZE: Pixels = px(2.);
1344
1345 let resizable = self.col_resizable
1346 && self
1347 .col_groups
1348 .get(ix)
1349 .map(|col| col.is_resizable())
1350 .unwrap_or(false);
1351 if !resizable {
1352 return div().into_any_element();
1353 }
1354
1355 let group_id = SharedString::from(format!("resizable-handle:{}", ix));
1356
1357 h_flex()
1358 .id(("resizable-handle", ix))
1359 .group(group_id.clone())
1360 .occlude()
1361 .cursor_col_resize()
1362 .h_full()
1363 .w(HANDLE_SIZE)
1364 .ml(-(HANDLE_SIZE))
1365 .justify_end()
1366 .items_center()
1367 .child(
1368 div()
1369 .h_full()
1370 .justify_center()
1371 .bg(cx.theme().table_row_border)
1372 .group_hover(&group_id, |this| this.bg(cx.theme().border).h_full())
1373 .w(px(1.)),
1374 )
1375 .on_drag_move(
1376 cx.listener(move |view, e: &DragMoveEvent<ResizeColumn>, window, cx| {
1377 match e.drag(cx) {
1378 ResizeColumn((entity_id, ix)) => {
1379 if cx.entity_id() != *entity_id {
1380 return;
1381 }
1382
1383 // sync col widths into real widths
1384 // TODO: Consider to remove this, this may not need now.
1385 // for (_, col_group) in view.col_groups.iter_mut().enumerate() {
1386 // col_group.width = col_group.bounds.size.width;
1387 // }
1388
1389 let ix = *ix;
1390 view.resizing_col = Some(ix);
1391
1392 let col_group = view
1393 .col_groups
1394 .get(ix)
1395 .expect("BUG: invalid col index")
1396 .clone();
1397
1398 view.resize_cols(
1399 ix,
1400 e.event.position.x - HANDLE_SIZE - col_group.bounds.left(),
1401 window,
1402 cx,
1403 );
1404
1405 // scroll the table if the drag is near the edge
1406 view.scroll_table_by_col_resizing(e.event.position, &col_group);
1407 }
1408 };
1409 }),
1410 )
1411 .on_drag(ResizeColumn((cx.entity_id(), ix)), |drag, _, _, cx| {
1412 cx.stop_propagation();
1413 cx.new(|_| drag.clone())
1414 })
1415 .on_mouse_up_out(
1416 MouseButton::Left,
1417 cx.listener(|view, _, _, cx| {
1418 if view.resizing_col.is_none() {
1419 return;
1420 }
1421
1422 view.resizing_col = None;
1423
1424 let new_widths = view.col_groups.iter().map(|g| g.width).collect();
1425 cx.emit(TableEvent::ColumnWidthsChanged(new_widths));
1426 cx.notify();
1427 }),
1428 )
1429 .into_any_element()
1430 }
1431
1432 /// Render the row header cell (when cell_selectable is enabled)
1433 fn render_row_header_cell(
1434 &self,
1435 row_ix: usize,
1436 is_head: bool,
1437 cx: &mut Context<Self>,
1438 ) -> impl IntoElement {
1439 div()
1440 .id(("row-header", row_ix))
1441 .w_3()
1442 .h_full()
1443 .border_r_1()
1444 .border_color(cx.theme().table_row_border)
1445 .bg(cx.theme().tokens.table_head)
1446 .flex_shrink_0()
1447 .table_cell_size(self.options.size)
1448 .when(!is_head, |this| {
1449 this.when(self.row_selectable, |this| {
1450 this.on_click(cx.listener(move |table, _, _window, cx| {
1451 table.set_selected_row(row_ix, cx);
1452 }))
1453 })
1454 })
1455 }
1456
1457 fn render_sort_icon(
1458 &self,
1459 col_ix: usize,
1460 col_group: &ColGroup,
1461 _: &mut Window,
1462 cx: &mut Context<Self>,
1463 ) -> Option<impl IntoElement> {
1464 if !self.sortable {
1465 return None;
1466 }
1467
1468 let Some(sort) = col_group.column.sort else {
1469 return None;
1470 };
1471
1472 let (icon, is_on) = match sort {
1473 ColumnSort::Ascending => (IconName::SortAscending, true),
1474 ColumnSort::Descending => (IconName::SortDescending, true),
1475 ColumnSort::Default => (IconName::ChevronsUpDown, false),
1476 };
1477
1478 Some(
1479 div()
1480 .id(("icon-sort", col_ix))
1481 .p(px(2.))
1482 .rounded(cx.theme().radius / 2.)
1483 .map(|this| match is_on {
1484 true => this,
1485 false => this.opacity(0.5),
1486 })
1487 .hover(|this| this.bg(cx.theme().tokens.secondary).opacity(7.))
1488 .active(|this| this.bg(cx.theme().tokens.secondary_active).opacity(1.))
1489 .on_click(
1490 cx.listener(move |table, _, window, cx| table.perform_sort(col_ix, window, cx)),
1491 )
1492 .child(
1493 Icon::new(icon)
1494 .size_3()
1495 .text_color(cx.theme().secondary_foreground),
1496 ),
1497 )
1498 }
1499
1500 /// Render the column header.
1501 /// The children must be one by one items.
1502 /// Because the horizontal scroll handle will use the child_item_bounds to
1503 /// calculate the item position for itself's `scroll_to_item` method.
1504 fn render_th(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) -> Div {
1505 let entity_id = cx.entity_id();
1506 let col_group = self.col_groups.get(col_ix).expect("BUG: invalid col index");
1507
1508 let movable = self.col_movable && col_group.column.movable;
1509 let paddings = col_group.column.paddings;
1510 let name = col_group.column.name.clone();
1511
1512 h_flex()
1513 .h_full()
1514 .child(
1515 self.render_cell(None, col_ix, window, cx)
1516 .id(("col-header", col_ix))
1517 .on_click(cx.listener(move |this, _, window, cx| {
1518 this.on_col_head_click(col_ix, window, cx);
1519 }))
1520 .child(
1521 h_flex()
1522 .size_full()
1523 .justify_between()
1524 .items_center()
1525 .child(self.delegate.render_th(col_ix, window, cx))
1526 .when_some(paddings, |this, paddings| {
1527 // Leave right space for the sort icon, if this column have custom padding
1528 let offset_pr =
1529 self.options.size.table_cell_padding().right - paddings.right;
1530 this.pr(offset_pr.max(px(0.)))
1531 })
1532 .children(self.render_sort_icon(col_ix, &col_group, window, cx)),
1533 )
1534 .when(movable, |this| {
1535 this.on_drag(
1536 DragColumn {
1537 entity_id,
1538 col_ix,
1539 name,
1540 width: col_group.width,
1541 },
1542 |drag, _, _, cx| {
1543 cx.stop_propagation();
1544 cx.new(|_| drag.clone())
1545 },
1546 )
1547 })
1548 .map(|this| {
1549 // Draw the insertion indicator on the left edge of the gap
1550 // column, or on the right edge of the last column for the
1551 // trailing gap. Use an absolutely positioned overlay instead
1552 // of a border, to avoid shifting the cell content.
1553 let last_gap = col_ix + 1 == self.col_groups.len();
1554 match self.col_drag_gap {
1555 Some(gap)
1556 if cx.has_active_drag()
1557 && (gap == col_ix || (last_gap && gap == col_ix + 1)) =>
1558 {
1559 let right_side = gap == col_ix + 1;
1560 this.relative().child(
1561 div()
1562 .absolute()
1563 .top_0()
1564 .bottom_0()
1565 .w(px(2.))
1566 .map(|d| if right_side { d.right_0() } else { d.left_0() })
1567 .bg(cx.theme().drag_border),
1568 )
1569 }
1570 _ => this,
1571 }
1572 }),
1573 )
1574 // resize handle
1575 .child(self.render_resize_handle(col_ix, window, cx))
1576 // to save the bounds of this col.
1577 .on_prepaint({
1578 let view = cx.entity().clone();
1579 move |bounds, _, cx| view.update(cx, |r, _| r.col_groups[col_ix].bounds = bounds)
1580 })
1581 }
1582
1583 /// Compute the visible non-fixed leaf-column range for header rendering.
1584 ///
1585 /// Returns `(visible_range, left_spacer_width)` where:
1586 /// - `visible_range` is the column-index range that should be rendered.
1587 /// - `left_spacer_width` is the total width of the off-screen left columns,
1588 /// used as a spacer div to keep visible columns at the correct position.
1589 ///
1590 /// On the first frame `self.bounds` is zero, so a fallback that covers all
1591 /// columns is returned to avoid a blank header on initial paint.
1592 fn calculate_visible_leaf_col_range(
1593 &self,
1594 left_columns_count: usize,
1595 ) -> (Range<usize>, Pixels) {
1596 let total_cols = self.col_groups.len();
1597
1598 if self.bounds.size.width == px(0.) {
1599 return (left_columns_count..total_cols, px(0.));
1600 }
1601
1602 let fixed_width = self.fixed_head_cols_bounds.size.width;
1603 let available_width = (self.bounds.size.width - fixed_width).max(px(0.));
1604 // The scroll handle offset is negative when scrolled right; negate it
1605 // to obtain a positive distance from the left edge of the scroll area.
1606 let scroll_x = (-self.horizontal_scroll_handle.offset().x).max(px(0.));
1607
1608 // Walk left-to-right through non-fixed columns to find the first one
1609 // whose right edge enters the viewport. The accumulated width of the
1610 // skipped columns becomes the left spacer width.
1611 let mut range_start = left_columns_count;
1612 let mut left_spacer = px(0.);
1613 let mut cumulative = px(0.);
1614 for i in left_columns_count..total_cols {
1615 let right_edge = cumulative + self.col_groups[i].width;
1616 if right_edge > scroll_x {
1617 range_start = i;
1618 left_spacer = cumulative;
1619 break;
1620 }
1621 cumulative = right_edge;
1622 }
1623
1624 // Continue from `range_start` (skipping already-scanned columns) to
1625 // find the last column still within the viewport. The 200 px overdraw
1626 // buffer prevents a visible flash when the user scrolls quickly.
1627 let right_bound = scroll_x + available_width + px(200.);
1628 let mut range_end = total_cols;
1629 let mut cumulative = left_spacer; // already summed widths before `range_start`
1630 for i in range_start..total_cols {
1631 cumulative += self.col_groups[i].width;
1632 if cumulative > right_bound {
1633 range_end = (i + 1).min(total_cols);
1634 break;
1635 }
1636 }
1637
1638 (range_start..range_end, left_spacer)
1639 }
1640
1641 fn render_table_header(
1642 &mut self,
1643 left_columns_count: usize,
1644 window: &mut Window,
1645 cx: &mut Context<Self>,
1646 ) -> impl IntoElement {
1647 let view = cx.entity().clone();
1648 let horizontal_scroll_handle = self.horizontal_scroll_handle.clone();
1649
1650 // Header leaf-column virtualization.
1651 //
1652 // `render_th` creates interactive elements with resize-handle listeners.
1653 // Calling it for every column every frame is O(n) in column count; with
1654 // 1000+ columns this alone drops FPS below 60 even in release mode.
1655 //
1656 // We restrict rendering to the columns currently visible inside the
1657 // overflow-scroll viewport, surrounding them with inert spacer divs:
1658 //
1659 // [left_spacer] [visible columns…] [right_spacer] [last_empty_col]
1660 //
1661 // The spacers preserve the flex container's total content width so that
1662 // the scrollbar range stays correct.
1663 let total_cols = self.col_groups.len();
1664 let (visible_col_range, left_spacer) =
1665 self.calculate_visible_leaf_col_range(left_columns_count);
1666
1667 let layout_len = self.header_layout.len();
1668
1669 // Reset fixed head columns bounds, if no fixed columns are present
1670 if left_columns_count == 0 {
1671 self.fixed_head_cols_bounds = Bounds::default();
1672 }
1673
1674 let mut header = self.delegate_mut().render_header(window, cx);
1675 let style = header.style().clone();
1676 let layout = self.header_layout.clone();
1677
1678 header
1679 .h_flex()
1680 .w_full()
1681 .flex_shrink_0()
1682 .bg(cx.theme().tokens.table_head)
1683 .text_color(cx.theme().table_head_foreground)
1684 .refine_style(&style)
1685 .on_drag_move(cx.listener(|table, e: &DragMoveEvent<DragColumn>, _, cx| {
1686 let drag = e.drag(cx);
1687 let (drag_entity_id, drag_col_ix) = (drag.entity_id, drag.col_ix);
1688
1689 let gap =
1690 if drag_entity_id == cx.entity_id() && e.bounds.contains(&e.event.position) {
1691 table.drag_gap_at(e.event.position.x, drag_col_ix)
1692 } else {
1693 None
1694 };
1695
1696 if table.col_drag_gap != gap {
1697 table.col_drag_gap = gap;
1698 cx.notify();
1699 }
1700 }))
1701 .on_drop(cx.listener(|table, drag: &DragColumn, window, cx| {
1702 if drag.entity_id != cx.entity_id() {
1703 return;
1704 }
1705
1706 // Insert the dragged column into the indicated gap.
1707 let Some(gap) = table.col_drag_gap.take() else {
1708 return;
1709 };
1710 let to_ix = if drag.col_ix < gap { gap - 1 } else { gap };
1711 table.move_column(drag.col_ix, to_ix, window, cx);
1712 }))
1713 .when(self.cell_selectable && self.row_header, |this| {
1714 this.child(self.render_row_header_cell(0, true, cx))
1715 })
1716 .when(left_columns_count > 0, |this| {
1717 let view = view.clone();
1718 // Render left fixed columns
1719 this.child(
1720 h_flex()
1721 .relative()
1722 .h_full()
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 h_flex()
1727 .min_w_full()
1728 .h(self.options.size.table_row_height())
1729 .border_b_1()
1730 .border_color(cx.theme().border)
1731 .children(row_cells.iter().filter_map(|cell| {
1732 if cell.start_leaf_col_ix < left_columns_count {
1733 if cell.is_leaf {
1734 if let Some(ix) = cell.leaf_col_ix {
1735 return Some(
1736 self.render_th(ix, window, cx)
1737 .into_any_element(),
1738 );
1739 }
1740 } else {
1741 return Some(
1742 self.delegate_mut()
1743 .render_group_th(
1744 &cell.label,
1745 cell.col_span,
1746 cell.width,
1747 window,
1748 cx,
1749 )
1750 .into_any_element(),
1751 );
1752 }
1753 }
1754 None
1755 }))
1756 }),
1757 ))
1758 .child(
1759 // Fixed columns border
1760 div()
1761 .absolute()
1762 .top_0()
1763 .right_0()
1764 .bottom_0()
1765 .w_0()
1766 .flex_shrink_0()
1767 .border_r_1()
1768 .border_color(cx.theme().border),
1769 )
1770 .on_prepaint(move |bounds, _, cx| {
1771 view.update(cx, |r, _| r.fixed_head_cols_bounds = bounds)
1772 }),
1773 )
1774 })
1775 .child(
1776 // Columns
1777 h_flex()
1778 .id("table-head")
1779 .size_full()
1780 .overflow_scroll()
1781 .relative()
1782 .track_scroll(&horizontal_scroll_handle)
1783 .bg(cx.theme().tokens.table_head)
1784 .child(v_flex().min_w_full().flex_shrink_0().children(
1785 layout.iter().enumerate().map(|(row_ix, row_cells)| {
1786 let is_leaf_row = row_ix + 1 == layout_len;
1787 h_flex()
1788 .min_w_full()
1789 .h(self.options.size.table_row_height())
1790 .border_b_1()
1791 .border_color(cx.theme().border)
1792 .map(|this| {
1793 if is_leaf_row {
1794 // Leaf row: apply the spacer virtualization pattern.
1795 // Only columns in `visible_range` are rendered; the two
1796 // spacer divs preserve the container's total content width
1797 // so the scrollbar range stays correct.
1798 this.when(left_spacer > px(0.), |r| {
1799 r.child(div().w(left_spacer).h_full().flex_shrink_0())
1800 })
1801 .children(row_cells.iter().filter_map(|cell| {
1802 if cell.is_leaf {
1803 let ix = cell.leaf_col_ix?;
1804 if !visible_col_range.contains(&ix) {
1805 return None;
1806 }
1807 Some(
1808 self.render_th(ix, window, cx)
1809 .into_any_element(),
1810 )
1811 } else {
1812 None
1813 }
1814 }))
1815 .when(visible_col_range.end < total_cols, |r| {
1816 let right_spacer: Pixels = self.col_groups
1817 [visible_col_range.end..total_cols]
1818 .iter()
1819 .map(|g| g.width)
1820 .sum();
1821 r.child(div().w(right_spacer).h_full().flex_shrink_0())
1822 })
1823 .child(self.delegate.render_last_empty_col(window, cx))
1824 } else {
1825 // Group header rows have far fewer cells (one per group),
1826 // so the cost of rendering all of them is negligible.
1827 this.children(row_cells.iter().filter_map(|cell| {
1828 if cell.start_leaf_col_ix >= left_columns_count {
1829 if cell.is_leaf {
1830 if let Some(ix) = cell.leaf_col_ix {
1831 return Some(
1832 self.render_th(ix, window, cx)
1833 .into_any_element(),
1834 );
1835 }
1836 } else {
1837 return Some(
1838 self.delegate_mut()
1839 .render_group_th(
1840 &cell.label,
1841 cell.col_span,
1842 cell.width,
1843 window,
1844 cx,
1845 )
1846 .into_any_element(),
1847 );
1848 }
1849 }
1850 None
1851 }))
1852 .child(self.delegate.render_last_empty_col(window, cx))
1853 }
1854 })
1855 }),
1856 )),
1857 )
1858 }
1859
1860 #[allow(clippy::too_many_arguments)]
1861 fn render_table_row(
1862 &mut self,
1863 row_ix: usize,
1864 rows_count: usize,
1865 left_columns_count: usize,
1866 col_sizes: Rc<Vec<gpui::Size<Pixels>>>,
1867 columns_count: usize,
1868 is_filled: bool,
1869 window: &mut Window,
1870 cx: &mut Context<Self>,
1871 ) -> Stateful<Div> {
1872 let horizontal_scroll_handle = self.horizontal_scroll_handle.clone();
1873 let is_stripe_row = self.options.stripe && row_ix % 2 != 0;
1874 let is_selected = self.selected_row == Some(row_ix);
1875 let view = cx.entity().clone();
1876 let row_height = self.options.size.table_row_height();
1877
1878 if row_ix < rows_count {
1879 let is_last_row = row_ix + 1 == rows_count;
1880 let need_render_border = is_selected || !is_last_row || !is_filled;
1881
1882 let mut tr = self.delegate.render_tr(row_ix, window, cx);
1883 let style = tr.style().clone();
1884
1885 tr.h_flex()
1886 .w_full()
1887 .h(row_height)
1888 .when(need_render_border, |this| {
1889 this.border_b_1().border_color(cx.theme().table_row_border)
1890 })
1891 .when(is_stripe_row, |this| this.bg(cx.theme().tokens.table_even))
1892 .refine_style(&style)
1893 .hover(|this| {
1894 if is_selected || self.right_clicked_row == Some(row_ix) {
1895 this
1896 } else {
1897 this.bg(cx.theme().tokens.table_hover)
1898 }
1899 })
1900 .when(self.cell_selectable && self.row_header, |this| {
1901 this.child(self.render_row_header_cell(row_ix, false, cx))
1902 })
1903 .when(left_columns_count > 0, |this| {
1904 // Left fixed columns
1905 this.child(
1906 h_flex()
1907 .relative()
1908 .h_full()
1909 .children({
1910 let mut items = Vec::with_capacity(left_columns_count);
1911
1912 (0..left_columns_count).for_each(|col_ix| {
1913 let is_cell_selected = self.selected_cell
1914 == Some((row_ix, col_ix))
1915 && self.selection_mode.is_cell();
1916 let is_cell_right_clicked =
1917 self.right_clicked_cell == Some((row_ix, col_ix));
1918
1919 items.push(
1920 self.render_col_wrap(Some(row_ix), col_ix, window, cx)
1921 .child(
1922 self.render_cell(Some(row_ix), col_ix, window, cx)
1923 .id(format!("table-cell:{}:{}", row_ix, col_ix))
1924 .relative()
1925 .child(self.measure_render_td(
1926 row_ix, col_ix, window, cx,
1927 ))
1928 .when(is_cell_selected, |this| {
1929 this.child(
1930 div()
1931 .absolute()
1932 .inset_0()
1933 .bg(cx.theme().tokens.table_active)
1934 .border_1()
1935 .border_color(
1936 cx.theme().table_active_border,
1937 ),
1938 )
1939 })
1940 .when(
1941 is_cell_right_clicked && !is_cell_selected,
1942 |this| {
1943 this.child(
1944 div()
1945 .absolute()
1946 .inset_0()
1947 .border_1()
1948 .border_color(
1949 cx.theme()
1950 .table_active_border
1951 .opacity(0.5),
1952 ),
1953 )
1954 },
1955 )
1956 .when(self.cell_selectable, |this| {
1957 this.on_click(cx.listener(
1958 move |table, e, window, cx| {
1959 table.on_cell_click(
1960 e, row_ix, col_ix, window, cx,
1961 );
1962 },
1963 ))
1964 .on_mouse_down(
1965 MouseButton::Right,
1966 cx.listener(
1967 move |table, e, window, cx| {
1968 table.on_cell_right_click(
1969 e, row_ix, col_ix, window,
1970 cx,
1971 );
1972 },
1973 ),
1974 )
1975 }),
1976 ),
1977 );
1978 });
1979
1980 items
1981 })
1982 .child(
1983 // Fixed columns border
1984 div()
1985 .absolute()
1986 .top_0()
1987 .right_0()
1988 .bottom_0()
1989 .w_0()
1990 .flex_shrink_0()
1991 .border_r_1()
1992 .border_color(cx.theme().border),
1993 ),
1994 )
1995 })
1996 .child(
1997 h_flex()
1998 .flex_1()
1999 .h_full()
2000 .overflow_hidden()
2001 .relative()
2002 .child(
2003 crate::virtual_list::virtual_list(
2004 view,
2005 row_ix,
2006 Axis::Horizontal,
2007 col_sizes,
2008 {
2009 move |table, visible_range: Range<usize>, window, cx| {
2010 table.update_visible_range_if_need(
2011 visible_range.clone(),
2012 Axis::Horizontal,
2013 window,
2014 cx,
2015 );
2016
2017 let mut items = Vec::with_capacity(
2018 visible_range.end - visible_range.start,
2019 );
2020
2021 visible_range.for_each(|col_ix| {
2022 let col_ix = col_ix + left_columns_count;
2023 let is_cell_selected = table.selected_cell
2024 == Some((row_ix, col_ix))
2025 && table.selection_mode.is_cell();
2026 let is_cell_right_clicked =
2027 table.right_clicked_cell == Some((row_ix, col_ix));
2028
2029 let el = table
2030 .render_col_wrap(Some(row_ix), col_ix, window, cx)
2031 .child(
2032 table
2033 .render_cell(
2034 Some(row_ix),
2035 col_ix,
2036 window,
2037 cx,
2038 )
2039 .id(format!(
2040 "table-cell-{}:{}",
2041 row_ix, col_ix
2042 ))
2043 .relative()
2044 .child(table.measure_render_td(
2045 row_ix, col_ix, window, cx,
2046 ))
2047 .when(is_cell_selected, |this| {
2048 this.child(
2049 div()
2050 .absolute()
2051 .inset_0()
2052 .bg(cx
2053 .theme()
2054 .tokens
2055 .table_active)
2056 .border_1()
2057 .border_color(
2058 cx.theme()
2059 .table_active_border,
2060 ),
2061 )
2062 })
2063 .when(
2064 is_cell_right_clicked
2065 && !is_cell_selected,
2066 |this| {
2067 this.child(
2068 div()
2069 .absolute()
2070 .inset_0()
2071 .border_1()
2072 .border_color(
2073 cx.theme()
2074 .table_active_border
2075 .opacity(0.5),
2076 ),
2077 )
2078 },
2079 )
2080 .when(table.cell_selectable, |this| {
2081 this.on_click(cx.listener(
2082 move |table, e, window, cx| {
2083 cx.stop_propagation();
2084 table.on_cell_click(
2085 e, row_ix, col_ix, window,
2086 cx,
2087 );
2088 },
2089 ))
2090 .on_mouse_down(
2091 MouseButton::Right,
2092 cx.listener(
2093 move |table, e, window, cx| {
2094 table.on_cell_right_click(
2095 e, row_ix, col_ix,
2096 window, cx,
2097 );
2098 },
2099 ),
2100 )
2101 }),
2102 );
2103
2104 items.push(el);
2105 });
2106
2107 items
2108 }
2109 },
2110 )
2111 .with_scroll_handle(&self.horizontal_scroll_handle),
2112 )
2113 .child(self.delegate.render_last_empty_col(window, cx)),
2114 )
2115 // Row selected style
2116 // Note: Don't show row selection if a cell is selected
2117 .when_some(self.selected_row, |this, _| {
2118 this.when(is_selected && self.selection_mode.is_row(), |this| {
2119 this.map(|this| {
2120 if cx.theme().list.active_highlight {
2121 this.border_color(gpui::transparent_white()).child(
2122 div()
2123 .top(if row_ix == 0 { px(0.) } else { px(-1.) })
2124 .left(px(0.))
2125 .right(px(0.))
2126 .bottom(px(-1.))
2127 .absolute()
2128 .bg(cx.theme().tokens.table_active)
2129 .border_1()
2130 .border_color(cx.theme().table_active_border),
2131 )
2132 } else {
2133 this.bg(cx.theme().tokens.accent)
2134 }
2135 })
2136 })
2137 })
2138 // Row right click row style
2139 .when(self.right_clicked_row == Some(row_ix), |this| {
2140 this.border_color(gpui::transparent_white()).child(
2141 div()
2142 .top(if row_ix == 0 { px(0.) } else { px(-1.) })
2143 .left(px(0.))
2144 .right(px(0.))
2145 .bottom(px(-1.))
2146 .absolute()
2147 .border_1()
2148 .border_color(cx.theme().selection),
2149 )
2150 })
2151 .on_mouse_down(
2152 MouseButton::Right,
2153 cx.listener(move |this, e, window, cx| {
2154 this.on_row_right_click(e, Some(row_ix), window, cx);
2155 }),
2156 )
2157 .on_click(cx.listener(move |this, e, window, cx| {
2158 this.on_row_left_click(e, row_ix, window, cx);
2159 }))
2160 } else {
2161 // Render fake rows to fill the rest table space
2162 self.delegate
2163 .render_tr(row_ix, window, cx)
2164 .h_flex()
2165 .w_full()
2166 .h(row_height)
2167 .border_b_1()
2168 .border_color(cx.theme().table_row_border)
2169 .when(is_stripe_row, |this| this.bg(cx.theme().tokens.table_even))
2170 .when(self.cell_selectable && self.row_header, |this| {
2171 // Render empty row header cell for fake rows
2172 this.child(
2173 div()
2174 .w(px(40.))
2175 .h_full()
2176 .flex_shrink_0()
2177 .table_cell_size(self.options.size),
2178 )
2179 })
2180 .children((0..columns_count).map(|col_ix| {
2181 h_flex()
2182 .left(horizontal_scroll_handle.offset().x)
2183 .child(self.render_cell(None, col_ix, window, cx))
2184 }))
2185 .child(self.delegate.render_last_empty_col(window, cx))
2186 }
2187 }
2188
2189 /// Calculate the extra rows needed to fill the table empty space when `stripe` is true.
2190 fn calculate_extra_rows_needed(
2191 &self,
2192 total_height: Pixels,
2193 actual_height: Pixels,
2194 row_height: Pixels,
2195 ) -> usize {
2196 let mut extra_rows_needed = 0;
2197
2198 let remaining_height = total_height - actual_height;
2199 if remaining_height > px(0.) {
2200 extra_rows_needed = (remaining_height / row_height).floor() as usize;
2201 }
2202
2203 extra_rows_needed
2204 }
2205
2206 #[inline]
2207 fn measure_render_td(
2208 &mut self,
2209 row_ix: usize,
2210 col_ix: usize,
2211 window: &mut Window,
2212 cx: &mut Context<Self>,
2213 ) -> impl IntoElement {
2214 if !crate::measure_enable() {
2215 return self
2216 .delegate
2217 .render_td(row_ix, col_ix, window, cx)
2218 .into_any_element();
2219 }
2220
2221 let start = std::time::Instant::now();
2222 let el = self.delegate.render_td(row_ix, col_ix, window, cx);
2223 self._measure.push(start.elapsed());
2224 el.into_any_element()
2225 }
2226
2227 fn measure(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
2228 if !crate::measure_enable() {
2229 return;
2230 }
2231
2232 // Print avg measure time of each td
2233 if self._measure.len() > 0 {
2234 let total = self
2235 ._measure
2236 .iter()
2237 .fold(Duration::default(), |acc, d| acc + *d);
2238 let avg = total / self._measure.len() as u32;
2239 eprintln!(
2240 "last render {} cells total: {:?}, avg: {:?}",
2241 self._measure.len(),
2242 total,
2243 avg,
2244 );
2245 }
2246 self._measure.clear();
2247 }
2248
2249 fn render_vertical_scrollbar(
2250 &mut self,
2251 _: &mut Window,
2252 _: &mut Context<Self>,
2253 ) -> Option<impl IntoElement> {
2254 Some(
2255 div()
2256 .absolute()
2257 .top(self.options.size.table_row_height() * self.header_layout.len().max(1) as f32)
2258 .right_0()
2259 .bottom_0()
2260 .w(Scrollbar::width())
2261 .child(
2262 Scrollbar::vertical(&self.vertical_scroll_handle)
2263 .viewport_from_layout()
2264 .max_fps(60),
2265 ),
2266 )
2267 }
2268
2269 fn render_horizontal_scrollbar(
2270 &mut self,
2271 _: &mut Window,
2272 _: &mut Context<Self>,
2273 ) -> impl IntoElement {
2274 div()
2275 .absolute()
2276 .left(self.fixed_head_cols_bounds.size.width)
2277 .right_0()
2278 .bottom_0()
2279 .h(Scrollbar::width())
2280 .child(Scrollbar::horizontal(&self.horizontal_scroll_handle).viewport_from_layout())
2281 }
2282}
2283
2284impl<D> Focusable for TableState<D>
2285where
2286 D: TableDelegate,
2287{
2288 fn focus_handle(&self, _cx: &gpui::App) -> FocusHandle {
2289 self.focus_handle.clone()
2290 }
2291}
2292impl<D> EventEmitter<TableEvent> for TableState<D> where D: TableDelegate {}
2293
2294impl<D> Render for TableState<D>
2295where
2296 D: TableDelegate,
2297{
2298 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2299 self.measure(window, cx);
2300
2301 let columns_count = self.delegate.columns_count(cx);
2302 let left_columns_count = self
2303 .col_groups
2304 .iter()
2305 .filter(|col| self.col_fixed && col.column.fixed == Some(ColumnFixed::Left))
2306 .count();
2307 let rows_count = self.delegate.rows_count(cx);
2308 let loading = self.delegate.loading(cx);
2309
2310 let row_height = self.options.size.table_row_height();
2311 let total_height = self
2312 .vertical_scroll_handle
2313 .0
2314 .borrow()
2315 .base_handle
2316 .bounds()
2317 .size
2318 .height;
2319 let actual_height = row_height * rows_count as f32;
2320 let extra_rows_count =
2321 self.calculate_extra_rows_needed(total_height, actual_height, row_height);
2322 let render_rows_count = if self.options.stripe {
2323 rows_count + extra_rows_count
2324 } else {
2325 rows_count
2326 };
2327 let right_clicked_row = self.right_clicked_row;
2328 let is_filled = total_height > Pixels::ZERO && total_height <= actual_height;
2329
2330 let loading_view = if loading {
2331 Some(
2332 self.delegate
2333 .render_loading(self.options.size, window, cx)
2334 .into_any_element(),
2335 )
2336 } else {
2337 None
2338 };
2339
2340 let empty_view = if rows_count == 0 {
2341 Some(
2342 div()
2343 .size_full()
2344 .child(self.delegate.render_empty(window, cx))
2345 .into_any_element(),
2346 )
2347 } else {
2348 None
2349 };
2350
2351 let inner_table = v_flex()
2352 .id("table-inner")
2353 .size_full()
2354 .overflow_hidden()
2355 .child(self.render_table_header(left_columns_count, window, cx))
2356 .context_menu({
2357 let view = cx.entity().clone();
2358 move |this, window: &mut Window, cx: &mut Context<PopupMenu>| {
2359 if let Some(row_ix) = view.read(cx).right_clicked_row {
2360 view.update(cx, |menu, cx| {
2361 menu.delegate_mut().context_menu(row_ix, this, window, cx)
2362 })
2363 } else {
2364 this
2365 }
2366 }
2367 })
2368 .map(|this| {
2369 if rows_count == 0 {
2370 this.children(empty_view)
2371 } else {
2372 this.child(
2373 h_flex().id("table-body").flex_grow_1().size_full().child(
2374 uniform_list(
2375 "table-uniform-list",
2376 render_rows_count,
2377 cx.processor(
2378 move |table, visible_range: Range<usize>, window, cx| {
2379 // Use `col.width` (always up-to-date) rather than
2380 // `col.bounds.size.width`, which is only set after
2381 // prepaint and is therefore zero on the first frame.
2382 let col_sizes: Rc<Vec<gpui::Size<Pixels>>> = Rc::new(
2383 table
2384 .col_groups
2385 .iter()
2386 .skip(left_columns_count)
2387 .map(|col| gpui::Size {
2388 width: col.width,
2389 height: px(0.),
2390 })
2391 .collect(),
2392 );
2393
2394 table.load_more_if_need(
2395 rows_count,
2396 visible_range.end,
2397 window,
2398 cx,
2399 );
2400 table.update_visible_range_if_need(
2401 visible_range.clone(),
2402 Axis::Vertical,
2403 window,
2404 cx,
2405 );
2406
2407 if visible_range.end > rows_count {
2408 table.scroll_to_row(
2409 std::cmp::min(
2410 visible_range.start,
2411 rows_count.saturating_sub(1),
2412 ),
2413 cx,
2414 );
2415 }
2416
2417 let mut items = Vec::with_capacity(
2418 visible_range.end.saturating_sub(visible_range.start),
2419 );
2420
2421 // Render fake rows to fill the table
2422 visible_range.for_each(|row_ix| {
2423 // Render real rows for available data
2424 items.push(table.render_table_row(
2425 row_ix,
2426 rows_count,
2427 left_columns_count,
2428 col_sizes.clone(),
2429 columns_count,
2430 is_filled,
2431 window,
2432 cx,
2433 ));
2434 });
2435
2436 items
2437 },
2438 ),
2439 )
2440 .flex_grow_1()
2441 .size_full()
2442 .with_sizing_behavior(ListSizingBehavior::Auto)
2443 .track_scroll(&self.vertical_scroll_handle)
2444 .into_any_element(),
2445 ),
2446 )
2447 }
2448 });
2449
2450 div()
2451 .size_full()
2452 .children(loading_view)
2453 .when(!loading, |this| {
2454 this.child(inner_table)
2455 .child(ScrollableMask::new(
2456 Axis::Horizontal,
2457 &self.horizontal_scroll_handle,
2458 ))
2459 // Keep vertical wheel scrolling from leaking into an
2460 // ancestor scroller. Skipped when the table is empty:
2461 // the `uniform_list` is not rendered then, so the
2462 // handle's offset and `max_offset` are stale.
2463 .when(rows_count > 0, |this| {
2464 this.child(ScrollableMask::new(
2465 Axis::Vertical,
2466 &self.vertical_scroll_handle.0.borrow().base_handle,
2467 ))
2468 })
2469 .when(right_clicked_row.is_some(), |this| {
2470 this.on_mouse_down_out(cx.listener(|this, e, window, cx| {
2471 this.on_row_right_click(e, None, window, cx);
2472 cx.notify();
2473 }))
2474 })
2475 })
2476 .on_prepaint({
2477 let state = cx.entity();
2478 move |bounds, _, cx| state.update(cx, |state, _| state.bounds = bounds)
2479 })
2480 .when(!window.is_inspector_picking(cx), |this| {
2481 this.child(
2482 div()
2483 .absolute()
2484 .top_0()
2485 .size_full()
2486 .when(self.options.scrollbar_visible.bottom, |this| {
2487 this.child(self.render_horizontal_scrollbar(window, cx))
2488 })
2489 .when(
2490 self.options.scrollbar_visible.right && rows_count > 0,
2491 |this| this.children(self.render_vertical_scrollbar(window, cx)),
2492 ),
2493 )
2494 })
2495 }
2496}