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