Skip to main content

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