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::{
16    AppContext, Axis, Bounds, ClickEvent, Context, Div, DragMoveEvent, ElementId, EventEmitter,
17    FocusHandle, Focusable, InteractiveElement, IntoElement, ListSizingBehavior, MouseButton,
18    MouseDownEvent, ParentElement, Pixels, Point, Render, ScrollStrategy, SharedString, Stateful,
19    StatefulInteractiveElement as _, Styled, Task, TextAlign, UniformListScrollHandle, Window, div,
20    prelude::FluentBuilder, px, uniform_list,
21};
22use rust_i18n::t;
23
24use super::*;
25
26/// Grab room on each side of a resize handle's hairline, so the divider can be
27/// caught without pixel-hunting. Both halves of the band are this wide, so
28/// widening the grab area stays symmetric about the boundary. `resizable`'s
29/// handle pads a hairline the same way, and by the same amount, see
30/// `crates/base/src/resizable/resize_handle.rs`.
31const HANDLE_PADDING: Pixels = px(4.);
32
33#[derive(Copy, Clone, Debug, PartialEq, Eq)]
34enum SelectionMode {
35    Column,
36    Row,
37    Cell,
38}
39
40impl SelectionMode {
41    #[inline(always)]
42    fn is_row(&self) -> bool {
43        matches!(self, SelectionMode::Row)
44    }
45
46    #[inline(always)]
47    fn is_column(&self) -> bool {
48        matches!(self, SelectionMode::Column)
49    }
50
51    #[inline(always)]
52    fn is_cell(&self) -> bool {
53        matches!(self, SelectionMode::Cell)
54    }
55}
56
57/// The current selection of a table, as one value.
58///
59/// Mirrors [`TableEvent::SelectRow`], [`TableEvent::SelectColumn`] and
60/// [`TableEvent::SelectCell`]. Match on it instead of combining
61/// [`TableState::selected_row`], [`TableState::selected_col`] and
62/// [`TableState::selected_cell`].
63#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
64pub enum TableSelection {
65    /// Nothing is selected.
66    #[default]
67    None,
68    /// A row is selected.
69    Row(usize),
70    /// A column is selected.
71    Column(usize),
72    /// A cell is selected, as `(row_ix, col_ix)`.
73    Cell(usize, usize),
74}
75
76/// The Table event.
77#[derive(Clone)]
78pub enum TableEvent {
79    /// Single click or move to selected row.
80    SelectRow(usize),
81    /// Double click on the row.
82    DoubleClickedRow(usize),
83    /// Selected column.
84    SelectColumn(usize),
85    /// A cell has been selected (clicked or navigated to via keyboard).
86    ///
87    /// Emitted when a cell is selected in cell selection mode.
88    /// The first `usize` is the row index, and the second `usize` is the column index.
89    ///
90    /// This event is also emitted when navigating between cells using keyboard shortcuts.
91    SelectCell(usize, usize),
92    /// A cell has been double-clicked.
93    ///
94    /// Emitted when a cell is double-clicked in cell selection mode.
95    /// The first `usize` is the row index, and the second `usize` is the column index.
96    ///
97    /// Use this event to trigger actions like opening a detail view or editing the cell content.
98    DoubleClickedCell(usize, usize),
99    /// The column widths have changed.
100    ///
101    /// The `Vec<Pixels>` contains the new widths of all columns.
102    ColumnWidthsChanged(Vec<Pixels>),
103    /// A column has been moved.
104    ///
105    /// The first `usize` is the original index of the column,
106    /// and the second `usize` is the new index of the column.
107    MoveColumn(usize, usize),
108    /// A row has been right-clicked.
109    ///
110    /// Contains the row index, or `None` if right-clicked on an empty area.
111    /// Use this event to show context menus for rows.
112    RightClickedRow(Option<usize>),
113    /// A cell has been right-clicked.
114    ///
115    /// Emitted when a cell is right-clicked in cell selection mode.
116    /// The first `usize` is the row index, and the second `usize` is the column index.
117    ///
118    /// Use this event to show context menus specific to the cell content.
119    /// The right-clicked cell is highlighted with a subtle border until another cell is clicked.
120    RightClickedCell(usize, usize),
121    /// The selection has been cleared.
122    ///
123    /// This event is emitted when the selection is cleared.
124    ClearSelection,
125}
126
127/// The visible range of the rows and columns.
128#[derive(Debug, Default)]
129pub struct TableVisibleRange {
130    /// The visible range of the rows.
131    rows: Range<usize>,
132    /// The visible range of the columns.
133    cols: Range<usize>,
134}
135
136impl TableVisibleRange {
137    /// Returns the visible range of the rows.
138    pub fn rows(&self) -> &Range<usize> {
139        &self.rows
140    }
141
142    /// Returns the visible range of the columns.
143    pub fn cols(&self) -> &Range<usize> {
144        &self.cols
145    }
146}
147
148/// Where a column resize started: the pointer's x at the press on the
149/// resize handle, and the column's width then.
150#[derive(Clone, Copy)]
151struct ResizeOrigin {
152    x: Pixels,
153    width: Pixels,
154}
155
156/// The state for [`DataTable`].
157///
158/// # Selection Modes
159///
160/// The table supports three selection modes:
161/// - **Row Selection**: Select entire rows (default mode)
162/// - **Column Selection**: Select entire columns
163/// - **Cell Selection**: Select individual cells
164///
165/// ## Cell Selection
166///
167/// When `cell_selectable` is enabled, users can:
168/// - Click on cells to select them
169/// - Right-click on cells to mark them for context menus
170/// - Double-click on cells to trigger actions
171/// - Navigate between cells using keyboard (arrow keys, Home, End, PageUp, PageDown, Tab)
172///
173/// When in cell selection mode, a row header column appears on the left side,
174/// allowing users to select entire rows by clicking on it.
175///
176/// # Events
177///
178/// The table emits the following events related to cell selection:
179/// - [`TableEvent::SelectCell`]: Emitted when a cell is selected
180/// - [`TableEvent::DoubleClickedCell`]: Emitted when a cell is double-clicked
181/// - [`TableEvent::RightClickedCell`]: Emitted when a cell is right-clicked
182///
183/// # Example
184///
185/// ```rust,ignore
186/// let table_state = cx.new(|cx| {
187///     TableState::new(delegate, window, cx)
188///         .cell_selectable(true)
189///         .row_selectable(true)
190/// });
191///
192/// // Subscribe to cell events
193/// cx.subscribe(&table_state, |this, table, event, cx| {
194///     match event {
195///         TableEvent::SelectCell(row_ix, col_ix) => {
196///             println!("Selected cell: ({}, {})", row_ix, col_ix);
197///         }
198///         TableEvent::DoubleClickedCell(row_ix, col_ix) => {
199///             println!("Double-clicked cell: ({}, {})", row_ix, col_ix);
200///         }
201///         _ => {}
202///     }
203/// });
204/// ```
205#[derive(Clone)]
206pub(crate) struct HeaderCell {
207    pub label: SharedString,
208    pub width: Pixels,
209    col_span: usize,
210    is_leaf: bool,
211    leaf_col_ix: Option<usize>,
212    start_leaf_col_ix: usize,
213}
214
215pub struct TableState<D: TableDelegate> {
216    focus_handle: FocusHandle,
217    delegate: D,
218    pub(super) options: TableOptions,
219    /// The bounds of the table container.
220    bounds: Bounds<Pixels>,
221    /// The bounds of the left fixed head cols.
222    fixed_head_cols_bounds: Bounds<Pixels>,
223    /// The bounds of the right fixed head cols.
224    fixed_right_head_cols_bounds: Bounds<Pixels>,
225
226    col_groups: Vec<ColGroup>,
227    header_layout: Vec<Vec<HeaderCell>>,
228
229    /// Whether the table can loop selection, default is true.
230    ///
231    /// When the prev/next selection is out of the table bounds, the selection will loop to the other side.
232    pub loop_selection: bool,
233    /// Whether the table can select column.
234    pub col_selectable: bool,
235    /// Whether the table can select row.
236    pub row_selectable: bool,
237    /// Whether a row click with the secondary modifier (⌘ on macOS, Ctrl
238    /// elsewhere) or Shift held selects the row, default is `true`.
239    ///
240    /// Set to `false` when the delegate keeps its own multi-row selection and
241    /// handles those clicks itself. The table then leaves its selected row
242    /// alone on a modified click, so a click that takes a row out of the
243    /// delegate's selection is not undone by the table selecting it.
244    ///
245    /// In cell selection without a row header, a modified click on the
246    /// selected cell does not escalate it to its row either.
247    select_on_modifier_click: bool,
248    /// Whether the table can select cell, default is false.
249    ///
250    /// When enabled:
251    /// - Users can click on individual cells to select them
252    /// - A row header column appears on the left for selecting entire rows
253    ///   (can be hidden via [`Self::row_header`])
254    /// - Keyboard navigation works at the cell level (arrow keys move between cells)
255    /// - Right-click and double-click events are supported for cells
256    pub cell_selectable: bool,
257    /// Whether the row header column is visible when `cell_selectable` is enabled,
258    /// default is `true`.
259    ///
260    /// Set to `false` to hide the narrow leftmost header column while keeping cell
261    /// selection — useful when you want to put your own content (e.g. a row index
262    /// column) on the left. When hidden, clicking the already-selected cell again
263    /// escalates the selection to the whole row so users can still pick rows; row
264    /// escalation requires `row_selectable` to be enabled.
265    pub row_header: bool,
266    /// Whether the table can sort.
267    pub sortable: bool,
268    /// Whether the table can resize columns.
269    pub col_resizable: bool,
270    /// Whether the table can move columns.
271    pub col_movable: bool,
272    /// Enable/disable fixed columns feature.
273    pub col_fixed: bool,
274
275    pub vertical_scroll_handle: UniformListScrollHandle,
276    pub horizontal_scroll_handle: VirtualListScrollHandle,
277
278    selected_row: Option<usize>,
279    selection_mode: SelectionMode,
280    right_clicked_row: Option<usize>,
281    right_clicked_cell: Option<(usize, usize)>,
282    selected_col: Option<usize>,
283    selected_cell: Option<(usize, usize)>,
284
285    /// The column index that is being resized.
286    resizing_col: Option<usize>,
287    /// Where the press on a resize handle was, and the column's width then.
288    resize_origin: Option<ResizeOrigin>,
289    /// The column a double-click on its resize handle just fitted.
290    ///
291    /// The double-click's second press also starts a drag on the handle, which
292    /// would move the fitted edge back under the pointer, so resize drags on
293    /// this column are ignored until the next single press.
294    fitted_col: Option<usize>,
295
296    /// The insertion gap index (`0..=cols_count`) while dragging a column
297    /// header: the dragged column will be inserted between the columns
298    /// `gap - 1` and `gap` on drop.
299    col_drag_gap: Option<usize>,
300
301    /// The visible range of the rows and columns.
302    visible_range: TableVisibleRange,
303
304    _measure: Vec<Duration>,
305    _load_more_task: Task<()>,
306}
307
308impl<D> TableState<D>
309where
310    D: TableDelegate,
311{
312    /// Create a new TableState with the given delegate.
313    pub fn new(delegate: D, _: &mut Window, cx: &mut Context<Self>) -> Self {
314        let mut this = Self {
315            focus_handle: cx.focus_handle().tab_stop(true),
316            options: TableOptions::default(),
317            delegate,
318            col_groups: Vec::new(),
319            header_layout: Vec::new(),
320            horizontal_scroll_handle: VirtualListScrollHandle::new(),
321            vertical_scroll_handle: UniformListScrollHandle::new(),
322            selection_mode: SelectionMode::Row,
323            selected_row: None,
324            right_clicked_row: None,
325            right_clicked_cell: None,
326            selected_col: None,
327            selected_cell: None,
328            resizing_col: None,
329            resize_origin: None,
330            fitted_col: None,
331            col_drag_gap: None,
332            bounds: Bounds::default(),
333            fixed_head_cols_bounds: Bounds::default(),
334            fixed_right_head_cols_bounds: Bounds::default(),
335            visible_range: TableVisibleRange::default(),
336            loop_selection: true,
337            col_selectable: true,
338            row_selectable: true,
339            select_on_modifier_click: true,
340            cell_selectable: false,
341            row_header: true,
342            sortable: true,
343            col_movable: true,
344            col_resizable: true,
345            col_fixed: true,
346            _load_more_task: Task::ready(()),
347            _measure: Vec::new(),
348        };
349
350        this.prepare_col_groups(cx);
351        this
352    }
353
354    /// Returns a reference to the delegate.
355    pub fn delegate(&self) -> &D {
356        &self.delegate
357    }
358
359    /// Returns a mutable reference to the delegate.
360    pub fn delegate_mut(&mut self) -> &mut D {
361        &mut self.delegate
362    }
363
364    /// Set to loop selection, default to true.
365    pub fn loop_selection(mut self, loop_selection: bool) -> Self {
366        self.loop_selection = loop_selection;
367        self
368    }
369
370    /// Set to enable/disable column movable, default to true.
371    pub fn col_movable(mut self, col_movable: bool) -> Self {
372        self.col_movable = col_movable;
373        self
374    }
375
376    /// Set to enable/disable column resizable, default to true.
377    pub fn col_resizable(mut self, col_resizable: bool) -> Self {
378        self.col_resizable = col_resizable;
379        self
380    }
381
382    /// Set to enable/disable column sortable, default true
383    pub fn sortable(mut self, sortable: bool) -> Self {
384        self.sortable = sortable;
385        self
386    }
387
388    /// Set to enable/disable row selectable, default true
389    pub fn row_selectable(mut self, row_selectable: bool) -> Self {
390        self.row_selectable = row_selectable;
391        self
392    }
393
394    /// Set whether a row click with the secondary modifier or Shift held
395    /// selects the row, default is `true`.
396    pub fn select_on_modifier_click(mut self, select_on_modifier_click: bool) -> Self {
397        self.select_on_modifier_click = select_on_modifier_click;
398        self
399    }
400
401    /// Set to enable/disable column selectable, default true
402    pub fn col_selectable(mut self, col_selectable: bool) -> Self {
403        self.col_selectable = col_selectable;
404        self
405    }
406
407    /// Set to enable/disable cell selection, default is false.
408    ///
409    /// When enabled:
410    /// - Individual cells become selectable by clicking
411    /// - A row header column appears on the left side (can be hidden via [`Self::row_header`])
412    /// - Keyboard navigation operates at the cell level
413    /// - Cell-specific events (SelectCell, DoubleClickedCell, RightClickedCell) are emitted
414    ///
415    /// # Example
416    ///
417    /// ```rust,ignore
418    /// let table_state = cx.new(|cx| {
419    ///     TableState::new(delegate, window, cx)
420    ///         .cell_selectable(true)  // Enable cell selection
421    ///         .row_selectable(true)   // Also allow row selection via row header
422    /// });
423    /// ```
424    pub fn cell_selectable(mut self, cell_selectable: bool) -> Self {
425        self.cell_selectable = cell_selectable;
426        self
427    }
428
429    /// Set whether the row header column is shown, default is `true`.
430    ///
431    /// Only effective when `cell_selectable` is `true` — otherwise the row header
432    /// column is never rendered. Hide it when you want to use the leftmost column
433    /// for your own content (e.g. a row index column).
434    ///
435    /// When hidden, the first click on a cell selects the cell; clicking the
436    /// already-selected cell again escalates to selecting the whole row, so users
437    /// can still pick rows without the dedicated header column. The row escalation
438    /// requires `row_selectable` to be enabled.
439    pub fn row_header(mut self, row_header: bool) -> Self {
440        self.row_header = row_header;
441        self
442    }
443
444    /// When we update columns or rows, we need to refresh the table.
445    pub fn refresh(&mut self, cx: &mut Context<Self>) {
446        self.prepare_col_groups(cx);
447    }
448
449    /// Scroll to the row at the given index.
450    pub fn scroll_to_row(&mut self, row_ix: usize, cx: &mut Context<Self>) {
451        self.vertical_scroll_handle
452            .scroll_to_item(row_ix, ScrollStrategy::Top);
453        cx.notify();
454    }
455
456    // Scroll to the column at the given index.
457    pub fn scroll_to_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
458        let scrollable_cols = self.scrollable_cols();
459        // Right-fixed columns are always in view.
460        if col_ix >= scrollable_cols.end {
461            return;
462        }
463        let col_ix = col_ix.saturating_sub(scrollable_cols.start);
464
465        // Resolve the offset here instead of deferring it to the virtual list.
466        //
467        // The header and the rows share `horizontal_scroll_handle`, but only
468        // the rows are a `VirtualList`, and a deferred `scroll_to_item` is
469        // applied during that list's prepaint — which runs *after* the header
470        // has already been rendered and prepainted with the old offset. The
471        // header would therefore stay one frame behind the rows.
472        match self.horizontal_offset_for_col(col_ix) {
473            Some(offset_x) => {
474                let mut offset = self.horizontal_scroll_handle.offset();
475                offset.x = offset_x;
476                self.horizontal_scroll_handle.set_offset(offset);
477            }
478            // Before the first layout the viewport size is unknown, let the
479            // virtual list resolve the offset once it has been laid out.
480            None => self
481                .horizontal_scroll_handle
482                .scroll_to_item(col_ix, ScrollStrategy::Top),
483        }
484
485        cx.notify();
486    }
487
488    /// The horizontal scroll offset that brings the scrollable (non-fixed)
489    /// column at `col_ix` fully into view.
490    ///
491    /// This mirrors the nearest-edge behavior of [`VirtualListScrollHandle::scroll_to_item`]
492    /// with [`ScrollStrategy::Top`]: an already visible column keeps the current
493    /// offset, otherwise the column is aligned to the edge it overflows. Both
494    /// of those move the offset towards a column that exists, so the result
495    /// never runs past the content and needs no extra clamping.
496    ///
497    /// Returns `None` when the viewport size is not known yet, or when `col_ix`
498    /// is out of range.
499    fn horizontal_offset_for_col(&self, col_ix: usize) -> Option<Pixels> {
500        let viewport_width = self.horizontal_scroll_handle.bounds().size.width;
501        if viewport_width <= px(0.) {
502            return None;
503        }
504
505        let cols = self.col_groups.get(self.scrollable_cols())?;
506        let col_left: Pixels = cols.get(..col_ix)?.iter().map(|col| col.width).sum();
507        let col_right = col_left + cols.get(col_ix)?.width;
508        let offset_x = self.horizontal_scroll_handle.offset().x;
509
510        Some(if col_left + offset_x < px(0.) {
511            -col_left
512        } else if col_right + offset_x > viewport_width {
513            viewport_width - col_right
514        } else {
515            offset_x
516        })
517    }
518
519    /// Returns the current selection as one value.
520    ///
521    /// A selected cell reports as [`TableSelection::Cell`] only; use
522    /// `selected_cell().map(|(row_ix, _)| row_ix)` when the cell's row is wanted.
523    pub fn selection(&self) -> TableSelection {
524        if let Some(row_ix) = self.selected_row() {
525            TableSelection::Row(row_ix)
526        } else if let Some(col_ix) = self.selected_col() {
527            TableSelection::Column(col_ix)
528        } else if let Some((row_ix, col_ix)) = self.selected_cell() {
529            TableSelection::Cell(row_ix, col_ix)
530        } else {
531            TableSelection::None
532        }
533    }
534
535    /// Returns the selected row index.
536    ///
537    /// `Some` only when a row itself is selected; a selected cell does not
538    /// count, see [`TableState::selection`].
539    pub fn selected_row(&self) -> Option<usize> {
540        self.selected_row.filter(|_| self.selection_mode.is_row())
541    }
542
543    /// Sets the selected row to the given index.
544    ///
545    /// This does not scroll; call [`TableState::scroll_to_row`] to reveal the
546    /// row. Clicks and keyboard navigation still scroll the selection into view.
547    pub fn set_selected_row(&mut self, row_ix: usize, cx: &mut Context<Self>) {
548        self.select_row(row_ix, false, cx);
549    }
550
551    pub(super) fn select_row(&mut self, row_ix: usize, scroll: bool, cx: &mut Context<Self>) {
552        let is_down = match self.selected_row {
553            Some(selected_row) => row_ix > selected_row,
554            None => true,
555        };
556
557        self.selection_mode = SelectionMode::Row;
558        self.right_clicked_row = None;
559        self.selected_row = Some(row_ix);
560        if scroll {
561            self.vertical_scroll_handle.scroll_to_item(
562                row_ix,
563                if is_down {
564                    ScrollStrategy::Bottom
565                } else {
566                    ScrollStrategy::Top
567                },
568            );
569        }
570        cx.emit(TableEvent::SelectRow(row_ix));
571        cx.emit(TableEvent::RightClickedRow(None));
572        cx.notify();
573    }
574
575    /// Returns the row that has been right clicked.
576    pub fn right_clicked_row(&self) -> Option<usize> {
577        self.right_clicked_row
578    }
579
580    /// Returns the cell that has been right clicked, as `(row_ix, col_ix)`.
581    pub fn right_clicked_cell(&self) -> Option<(usize, usize)> {
582        self.right_clicked_cell
583    }
584
585    /// Set or clear the right-clicked row state.
586    ///
587    /// Pass `None` to clear — useful when opening a header context menu
588    /// to prevent the row context menu from appearing simultaneously.
589    pub fn set_right_clicked_row(&mut self, row: Option<usize>, cx: &mut Context<Self>) {
590        self.right_clicked_row = row;
591        cx.notify();
592    }
593
594    /// Returns the selected column index.
595    ///
596    /// `Some` only when a column itself is selected; a selected cell does not
597    /// count, see [`TableState::selection`].
598    pub fn selected_col(&self) -> Option<usize> {
599        self.selected_col
600            .filter(|_| self.selection_mode.is_column())
601    }
602
603    /// Sets the selected col to the given index.
604    ///
605    /// This does not scroll; call [`TableState::scroll_to_col`] to reveal the
606    /// column. Clicks and keyboard navigation still scroll the selection into view.
607    pub fn set_selected_col(&mut self, col_ix: usize, cx: &mut Context<Self>) {
608        self.select_col(col_ix, false, cx);
609    }
610
611    fn select_col(&mut self, col_ix: usize, scroll: bool, cx: &mut Context<Self>) {
612        self.selection_mode = SelectionMode::Column;
613        self.selected_col = Some(col_ix);
614        if scroll {
615            self.scroll_to_col(col_ix, cx);
616        }
617        cx.emit(TableEvent::SelectColumn(col_ix));
618        cx.notify();
619    }
620
621    /// Returns the selected cell as `(row_ix, col_ix)`.
622    ///
623    /// `Some` only when a cell is selected; see [`TableState::selection`].
624    ///
625    /// # Example
626    ///
627    /// ```rust,ignore
628    /// if let Some((row_ix, col_ix)) = table_state.read(cx).selected_cell() {
629    ///     println!("Selected cell: ({}, {})", row_ix, col_ix);
630    /// }
631    /// ```
632    pub fn selected_cell(&self) -> Option<(usize, usize)> {
633        self.selected_cell.filter(|_| self.selection_mode.is_cell())
634    }
635
636    /// Sets the selected cell to the given row and column indices.
637    ///
638    /// This method:
639    /// - Switches the table to cell selection mode
640    /// - Does not scroll; call [`TableState::scroll_to_row`] and
641    ///   [`TableState::scroll_to_col`] to reveal the cell
642    /// - Emits a [`TableEvent::SelectCell`] event
643    ///
644    /// # Example
645    ///
646    /// ```rust,ignore
647    /// // Select the cell at row 5, column 3
648    /// table_state.update(cx, |state, cx| {
649    ///     state.set_selected_cell(5, 3, cx);
650    /// });
651    /// ```
652    pub fn set_selected_cell(&mut self, row_ix: usize, col_ix: usize, cx: &mut Context<Self>) {
653        self.select_cell(row_ix, col_ix, false, cx);
654    }
655
656    fn select_cell(&mut self, row_ix: usize, col_ix: usize, scroll: bool, cx: &mut Context<Self>) {
657        self.selection_mode = SelectionMode::Cell;
658        self.selected_cell = Some((row_ix, col_ix));
659        self.right_clicked_cell = None;
660
661        if scroll {
662            self.vertical_scroll_handle
663                .scroll_to_item(row_ix, ScrollStrategy::Center);
664            self.scroll_to_col(col_ix, cx);
665        }
666
667        cx.emit(TableEvent::SelectCell(row_ix, col_ix));
668        cx.notify();
669    }
670
671    /// Sets the selection as one value; [`TableSelection::None`] clears it.
672    ///
673    /// Like the matching `set_selected_*` it does not scroll, and emits as the matching `set_selected_*` or
674    /// [`TableState::clear_selection`] call would.
675    pub fn set_selection(&mut self, selection: TableSelection, cx: &mut Context<Self>) {
676        match selection {
677            TableSelection::None => self.clear_selection(cx),
678            TableSelection::Row(row_ix) => self.set_selected_row(row_ix, cx),
679            TableSelection::Column(col_ix) => self.set_selected_col(col_ix, cx),
680            TableSelection::Cell(row_ix, col_ix) => self.set_selected_cell(row_ix, col_ix, cx),
681        }
682    }
683
684    /// Clear the selection of the table.
685    pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
686        self.selection_mode = SelectionMode::Row;
687        self.selected_row = None;
688        self.selected_col = None;
689        self.selected_cell = None;
690        cx.emit(TableEvent::ClearSelection);
691        cx.notify();
692    }
693
694    /// Returns the visible range of the rows and columns.
695    ///
696    /// See [`TableVisibleRange`].
697    pub fn visible_range(&self) -> &TableVisibleRange {
698        &self.visible_range
699    }
700
701    /// Dump the header row of the table.
702    ///
703    /// Batched exporters can read the headers once with this, then stream the
704    /// rows with [`Self::dump_range`].
705    pub fn headers(&self, cx: &App) -> Vec<String> {
706        let columns_count = self.delegate.columns_count(cx);
707        let mut headers = Vec::with_capacity(columns_count);
708        for col_ix in 0..columns_count {
709            let column = self.delegate.column(col_ix, cx);
710            headers.push(column.name.to_string());
711        }
712
713        headers
714    }
715
716    /// Dump table data.
717    ///
718    /// Returns a tuple of (headers, rows) where each row is a vector of cell values.
719    ///
720    /// This materializes the complete table in memory. For large tables, prefer
721    /// [`Self::dump_range`] and process rows in batches.
722    pub fn dump(&self, cx: &App) -> (Vec<String>, Vec<Vec<String>>) {
723        self.dump_range(0..self.delegate.rows_count(cx), cx)
724    }
725
726    /// Dump table data for the specified row range.
727    ///
728    /// Returns the same `(headers, rows)` shape as [`Self::dump`], with only
729    /// the rows inside the clamped range.
730    ///
731    /// The requested range is clamped to the table's current row count. For
732    /// large tables, callers can invoke this repeatedly with bounded ranges.
733    pub fn dump_range(&self, range: Range<usize>, cx: &App) -> (Vec<String>, Vec<Vec<String>>) {
734        let columns_count = self.delegate.columns_count(cx);
735        let rows_count = self.delegate.rows_count(cx);
736        let start = range.start.min(rows_count);
737        let end = range.end.min(rows_count).max(start);
738
739        let mut rows = Vec::with_capacity(end - start);
740        for row_ix in start..end {
741            let mut row = Vec::with_capacity(columns_count);
742            for col_ix in 0..columns_count {
743                row.push(self.delegate.cell_text(row_ix, col_ix, cx));
744            }
745            rows.push(row);
746        }
747
748        (self.headers(cx), rows)
749    }
750
751    /// Re-compute the header layout from the current delegate.
752    ///
753    /// Call this after changing delegate state that affects `group_headers`.
754    pub fn refresh_header_layout(&mut self, cx: &mut Context<Self>) {
755        self.update_header_layout(cx);
756        cx.notify();
757    }
758
759    fn prepare_col_groups(&mut self, cx: &mut Context<Self>) {
760        self.col_groups = (0..self.delegate.columns_count(cx))
761            .map(|col_ix| {
762                let column = self.delegate().column(col_ix, cx);
763                ColGroup {
764                    width: column.width,
765                    bounds: Bounds::default(),
766                    column,
767                }
768            })
769            .collect();
770
771        self.update_header_layout(cx);
772    }
773
774    fn update_header_layout(&mut self, cx: &mut Context<Self>) {
775        let group_rows = self.delegate.group_headers(cx);
776
777        let mut layout = match group_rows.as_ref() {
778            Some(rows) => Vec::with_capacity(rows.len() + 1),
779            None => Vec::with_capacity(1),
780        };
781
782        if let Some(group_rows) = group_rows {
783            for row in group_rows {
784                let mut cell_row = Vec::with_capacity(row.len());
785                let mut current_leaf_ix = 0;
786                for group in row {
787                    let mut width = px(0.);
788                    let start_leaf_col_ix = current_leaf_ix;
789                    for i in 0..group.span {
790                        if current_leaf_ix + i < self.col_groups.len() {
791                            width += self.col_groups[current_leaf_ix + i].width;
792                        }
793                    }
794                    current_leaf_ix += group.span;
795                    cell_row.push(HeaderCell {
796                        label: group.label.clone(),
797                        width,
798                        col_span: group.span,
799                        is_leaf: false,
800                        leaf_col_ix: None,
801                        start_leaf_col_ix,
802                    });
803                }
804                layout.push(cell_row);
805            }
806        }
807
808        let mut leaf_row = Vec::with_capacity(self.col_groups.len());
809        for (ix, group) in self.col_groups.iter().enumerate() {
810            leaf_row.push(HeaderCell {
811                label: group.column.name.clone(),
812                width: group.width,
813                col_span: 1,
814                is_leaf: true,
815                leaf_col_ix: Some(ix),
816                start_leaf_col_ix: ix,
817            });
818        }
819        layout.push(leaf_row);
820
821        self.header_layout = layout;
822    }
823
824    fn fixed_cols_count(&self, side: ColumnFixed) -> usize {
825        if !self.col_fixed {
826            return 0;
827        }
828
829        self.col_groups
830            .iter()
831            .filter(|col| col.column.fixed == Some(side))
832            .count()
833    }
834
835    /// The columns between the left and right fixed columns, which scroll
836    /// horizontally.
837    ///
838    /// Left-fixed columns are the leading ones and right-fixed columns the
839    /// trailing ones, so this is everything in between.
840    fn scrollable_cols(&self) -> Range<usize> {
841        let total = self.col_groups.len();
842        let left = self.fixed_cols_count(ColumnFixed::Left).min(total);
843        let right = self.fixed_cols_count(ColumnFixed::Right).min(total - left);
844        left..total - right
845    }
846
847    /// The fixed side of the column at `col_ix`, `None` for a scrollable column.
848    fn col_fixed_side(&self, col_ix: usize) -> Option<ColumnFixed> {
849        let scrollable_cols = self.scrollable_cols();
850        if col_ix < scrollable_cols.start {
851            Some(ColumnFixed::Left)
852        } else if col_ix >= scrollable_cols.end {
853            Some(ColumnFixed::Right)
854        } else {
855            None
856        }
857    }
858
859    /// One header row. An unset header height matches the body rows.
860    fn header_row_height(&self) -> Pixels {
861        self.options
862            .header_row_height
863            .unwrap_or(self.options.size.table_row_height())
864    }
865
866    /// Every header row, including column-group rows. An empty layout still
867    /// reserves one row, matching the vertical scrollbar's top inset.
868    fn header_band_height(&self) -> Pixels {
869        self.header_row_height() * self.header_layout.len().max(1) as f32
870    }
871
872    fn page_item_count(&self) -> usize {
873        let row_height = self.options.size.table_row_height();
874        let body_height = (self.bounds.size.height - self.header_band_height()).max(px(0.));
875        let count = (body_height / row_height).floor() as usize;
876        count.max(1)
877    }
878
879    fn on_row_right_click(
880        &mut self,
881        _: &MouseDownEvent,
882        row_ix: Option<usize>,
883        _: &mut Window,
884        cx: &mut Context<Self>,
885    ) {
886        self.right_clicked_row = row_ix;
887        self.right_clicked_cell = None;
888        cx.emit(TableEvent::RightClickedRow(row_ix));
889    }
890
891    fn on_cell_right_click(
892        &mut self,
893        _: &MouseDownEvent,
894        row_ix: usize,
895        col_ix: usize,
896        _: &mut Window,
897        cx: &mut Context<Self>,
898    ) {
899        if !self.cell_selectable {
900            return;
901        }
902
903        cx.stop_propagation();
904        self.right_clicked_cell = Some((row_ix, col_ix));
905        self.right_clicked_row = None;
906        cx.emit(TableEvent::RightClickedCell(row_ix, col_ix));
907    }
908
909    fn on_row_left_click(
910        &mut self,
911        e: &ClickEvent,
912        row_ix: usize,
913        _: &mut Window,
914        cx: &mut Context<Self>,
915    ) {
916        if !self.row_selectable {
917            return;
918        }
919
920        cx.stop_propagation();
921        if self.selects_row_on_click(e, cx) {
922            self.select_row(row_ix, true, cx);
923        }
924
925        if e.click_count() == 2 {
926            cx.emit(TableEvent::DoubleClickedRow(row_ix));
927        }
928    }
929
930    /// Whether a click on a row selects it, see `select_on_modifier_click`.
931    fn selects_row_on_click(&self, e: &ClickEvent, cx: &App) -> bool {
932        let modifiers = e.modifiers();
933        self.select_on_modifier_click || !(modifiers.secondary(cx) || modifiers.shift)
934    }
935
936    fn on_col_head_click(&mut self, col_ix: usize, _: &mut Window, cx: &mut Context<Self>) {
937        if !self.col_selectable {
938            return;
939        }
940
941        let Some(col_group) = self.col_groups.get(col_ix) else {
942            return;
943        };
944
945        if !col_group.column.selectable {
946            return;
947        }
948
949        self.select_col(col_ix, true, cx)
950    }
951
952    fn on_cell_click(
953        &mut self,
954        e: &ClickEvent,
955        row_ix: usize,
956        col_ix: usize,
957        _: &mut Window,
958        cx: &mut Context<Self>,
959    ) {
960        if !self.cell_selectable {
961            return;
962        }
963
964        cx.stop_propagation();
965
966        let is_double_click = e.click_count() == 2;
967
968        // When the row header column is hidden, a single click on the
969        // already-selected cell escalates the selection to the entire row —
970        // giving users a way to pick rows without the dedicated header column.
971        // Double-clicks are passed through to `DoubleClickedCell` and never
972        // trigger the escalation.
973        let is_reselect = self.selected_cell() == Some((row_ix, col_ix));
974        let should_escalate_to_row = !self.row_header
975            && self.row_selectable
976            && is_reselect
977            && !is_double_click
978            && self.selects_row_on_click(e, cx);
979        if should_escalate_to_row {
980            self.select_row(row_ix, true, cx);
981            return;
982        }
983
984        self.select_cell(row_ix, col_ix, true, cx);
985
986        if is_double_click {
987            cx.emit(TableEvent::DoubleClickedCell(row_ix, col_ix));
988        }
989    }
990
991    fn has_selection(&self) -> bool {
992        self.selection() != TableSelection::None
993    }
994
995    pub(super) fn action_cancel(&mut self, _: &Cancel, _: &mut Window, cx: &mut Context<Self>) {
996        if self.has_selection() {
997            self.clear_selection(cx);
998            return;
999        }
1000        cx.propagate();
1001    }
1002
1003    pub(super) fn action_select_prev(
1004        &mut self,
1005        _: &SelectUp,
1006        _: &mut Window,
1007        cx: &mut Context<Self>,
1008    ) {
1009        let rows_count = self.delegate.rows_count(cx);
1010        if rows_count < 1 {
1011            return;
1012        }
1013
1014        // Cell selection mode: move up within the same column
1015        if self.selection_mode.is_cell() {
1016            if let Some((row_ix, col_ix)) = self.selected_cell {
1017                let new_row = if row_ix > 0 {
1018                    row_ix.saturating_sub(1)
1019                } else if self.loop_selection {
1020                    rows_count.saturating_sub(1)
1021                } else {
1022                    row_ix
1023                };
1024                self.select_cell(new_row, col_ix, true, cx);
1025            } else {
1026                // No cell selected, select first cell
1027                self.select_cell(0, 0, true, cx);
1028            }
1029            return;
1030        }
1031
1032        // Row selection mode
1033        if !self.row_selectable {
1034            return;
1035        }
1036        let mut selected_row = self.selected_row.unwrap_or(0);
1037        if selected_row > 0 {
1038            selected_row = selected_row.saturating_sub(1);
1039        } else {
1040            if self.loop_selection {
1041                selected_row = rows_count.saturating_sub(1);
1042            }
1043        }
1044
1045        self.select_row(selected_row, true, cx);
1046    }
1047
1048    pub(super) fn action_select_next(
1049        &mut self,
1050        _: &SelectDown,
1051        _: &mut Window,
1052        cx: &mut Context<Self>,
1053    ) {
1054        let rows_count = self.delegate.rows_count(cx);
1055        if rows_count < 1 {
1056            return;
1057        }
1058
1059        // Cell selection mode: move down within the same column
1060        if self.selection_mode.is_cell() {
1061            if let Some((row_ix, col_ix)) = self.selected_cell {
1062                let new_row = if row_ix < rows_count.saturating_sub(1) {
1063                    row_ix + 1
1064                } else if self.loop_selection {
1065                    0
1066                } else {
1067                    row_ix
1068                };
1069                self.select_cell(new_row, col_ix, true, cx);
1070            } else {
1071                // No cell selected, select first cell
1072                self.select_cell(0, 0, true, cx);
1073            }
1074            return;
1075        }
1076
1077        // Row selection mode
1078        if !self.row_selectable {
1079            return;
1080        }
1081        let selected_row = match self.selected_row {
1082            Some(selected_row) if selected_row < rows_count.saturating_sub(1) => selected_row + 1,
1083            Some(selected_row) => {
1084                if self.loop_selection {
1085                    0
1086                } else {
1087                    selected_row
1088                }
1089            }
1090            _ => 0,
1091        };
1092
1093        self.select_row(selected_row, true, cx);
1094    }
1095
1096    pub(super) fn action_select_first_column(
1097        &mut self,
1098        _: &SelectFirst,
1099        _: &mut Window,
1100        cx: &mut Context<Self>,
1101    ) {
1102        // Cell selection mode: move to first cell in current row
1103        if self.selection_mode.is_cell() {
1104            if let Some((row_ix, _)) = self.selected_cell {
1105                self.select_cell(row_ix, 0, true, cx);
1106            } else {
1107                // No cell selected, select first cell of first row
1108                self.select_cell(0, 0, true, cx);
1109            }
1110            return;
1111        }
1112
1113        // Row selection mode: Home goes to the first row, as in a list
1114        if self.selection_mode.is_row() && self.row_selectable {
1115            if self.delegate.rows_count(cx) > 0 {
1116                self.select_row(0, true, cx);
1117            }
1118            return;
1119        }
1120
1121        // Column selection mode
1122        self.select_col(0, true, cx);
1123    }
1124
1125    pub(super) fn action_select_last_column(
1126        &mut self,
1127        _: &SelectLast,
1128        _: &mut Window,
1129        cx: &mut Context<Self>,
1130    ) {
1131        let columns_count = self.delegate.columns_count(cx);
1132
1133        // Cell selection mode: move to last cell in current row
1134        if self.selection_mode.is_cell() {
1135            if let Some((row_ix, _)) = self.selected_cell {
1136                self.select_cell(row_ix, columns_count.saturating_sub(1), true, cx);
1137            } else {
1138                // No cell selected, select last cell of first row
1139                self.select_cell(0, columns_count.saturating_sub(1), true, cx);
1140            }
1141            return;
1142        }
1143
1144        // Row selection mode: End goes to the last row, as in a list
1145        if self.selection_mode.is_row() && self.row_selectable {
1146            let rows_count = self.delegate.rows_count(cx);
1147            if rows_count > 0 {
1148                self.select_row(rows_count - 1, true, cx);
1149            }
1150            return;
1151        }
1152
1153        // Column selection mode
1154        self.select_col(columns_count.saturating_sub(1), true, cx);
1155    }
1156
1157    pub(super) fn action_select_page_up(
1158        &mut self,
1159        _: &SelectPageUp,
1160        _: &mut Window,
1161        cx: &mut Context<Self>,
1162    ) {
1163        let step = self.page_item_count();
1164
1165        // Cell selection mode: move up by page within the same column
1166        if self.selection_mode.is_cell() {
1167            if let Some((row_ix, col_ix)) = self.selected_cell {
1168                let target = row_ix.saturating_sub(step);
1169                self.select_cell(target, col_ix, true, cx);
1170            } else {
1171                // No cell selected, select first cell
1172                self.select_cell(0, 0, true, cx);
1173            }
1174            return;
1175        }
1176
1177        // Row selection mode
1178        if !self.row_selectable {
1179            return;
1180        }
1181        let current = self.selected_row.unwrap_or(0);
1182        let target = current.saturating_sub(step);
1183        self.select_row(target, true, cx);
1184    }
1185
1186    pub(super) fn action_select_page_down(
1187        &mut self,
1188        _: &SelectPageDown,
1189        _: &mut Window,
1190        cx: &mut Context<Self>,
1191    ) {
1192        let rows_count = self.delegate.rows_count(cx);
1193        if rows_count == 0 {
1194            return;
1195        }
1196
1197        let step = self.page_item_count();
1198
1199        // Cell selection mode: move down by page within the same column
1200        if self.selection_mode.is_cell() {
1201            if let Some((row_ix, col_ix)) = self.selected_cell {
1202                let max_row = rows_count.saturating_sub(1);
1203                let target = (row_ix + step).min(max_row);
1204                self.select_cell(target, col_ix, true, cx);
1205            } else {
1206                // No cell selected, select first cell
1207                self.select_cell(0, 0, true, cx);
1208            }
1209            return;
1210        }
1211
1212        // Row selection mode
1213        if !self.row_selectable {
1214            return;
1215        }
1216        let current = self.selected_row.unwrap_or(0);
1217        let max_row = rows_count.saturating_sub(1);
1218        let target = (current + step).min(max_row);
1219        self.select_row(target, true, cx);
1220    }
1221
1222    pub(super) fn action_select_prev_col(
1223        &mut self,
1224        _: &SelectPrevColumn,
1225        _: &mut Window,
1226        cx: &mut Context<Self>,
1227    ) {
1228        let columns_count = self.delegate.columns_count(cx);
1229
1230        // Cell selection mode: move left within the same row
1231        if self.selection_mode.is_cell() {
1232            if let Some((row_ix, col_ix)) = self.selected_cell {
1233                let new_col = if col_ix > 0 {
1234                    col_ix.saturating_sub(1)
1235                } else if self.loop_selection {
1236                    columns_count.saturating_sub(1)
1237                } else {
1238                    col_ix
1239                };
1240                self.select_cell(row_ix, new_col, true, cx);
1241            } else {
1242                // No cell selected, select first cell
1243                self.select_cell(0, 0, true, cx);
1244            }
1245            return;
1246        }
1247
1248        // Column selection mode
1249        let mut selected_col = self.selected_col.unwrap_or(0);
1250        if selected_col > 0 {
1251            selected_col = selected_col.saturating_sub(1);
1252        } else {
1253            if self.loop_selection {
1254                selected_col = columns_count.saturating_sub(1);
1255            }
1256        }
1257        self.select_col(selected_col, true, cx);
1258    }
1259
1260    pub(super) fn action_select_next_col(
1261        &mut self,
1262        _: &SelectNextColumn,
1263        _: &mut Window,
1264        cx: &mut Context<Self>,
1265    ) {
1266        let columns_count = self.delegate.columns_count(cx);
1267
1268        // Cell selection mode: move right within the same row
1269        if self.selection_mode.is_cell() {
1270            if let Some((row_ix, col_ix)) = self.selected_cell {
1271                let new_col = if col_ix < columns_count.saturating_sub(1) {
1272                    col_ix + 1
1273                } else if self.loop_selection {
1274                    0
1275                } else {
1276                    col_ix
1277                };
1278                self.select_cell(row_ix, new_col, true, cx);
1279            } else {
1280                // No cell selected, select first cell
1281                self.select_cell(0, 0, true, cx);
1282            }
1283            return;
1284        }
1285
1286        // Column selection mode
1287        let mut selected_col = self.selected_col.unwrap_or(0);
1288        if selected_col < columns_count.saturating_sub(1) {
1289            selected_col += 1;
1290        } else {
1291            if self.loop_selection {
1292                selected_col = 0;
1293            }
1294        }
1295
1296        self.select_col(selected_col, true, cx);
1297    }
1298
1299    /// Scroll table when mouse position is near the edge of the table bounds.
1300    fn scroll_table_by_col_resizing(
1301        &mut self,
1302        mouse_position: Point<Pixels>,
1303        col_group: &ColGroup,
1304    ) {
1305        // Do nothing if pos out of the table bounds right for avoid scroll to the right.
1306        if mouse_position.x > self.bounds.right() {
1307            return;
1308        }
1309
1310        let mut offset = self.horizontal_scroll_handle.offset();
1311        let col_bounds = col_group.bounds;
1312
1313        if mouse_position.x < self.bounds.left()
1314            && col_bounds.right() < self.bounds.left() + px(20.)
1315        {
1316            offset.x += px(1.);
1317        } else if mouse_position.x > self.bounds.right()
1318            && col_bounds.right() > self.bounds.right() - px(20.)
1319        {
1320            offset.x -= px(1.);
1321        }
1322
1323        self.horizontal_scroll_handle.set_offset(offset);
1324    }
1325
1326    /// The width column `col_ix` is drawn at now, or `None` past the last
1327    /// column.
1328    ///
1329    /// This is the table's own width, which follows a drag or a fit as it
1330    /// happens; the delegate's [`Column::width`] is read again only on
1331    /// [`Self::refresh`].
1332    pub fn col_width(&self, col_ix: usize) -> Option<Pixels> {
1333        self.col_groups.get(col_ix).map(|group| group.width)
1334    }
1335
1336    /// Fits column `col_ix` to its content, as a double-click on its resize
1337    /// handle does.
1338    ///
1339    /// The width is [`TableDelegate::fit_column`] plus the cell padding,
1340    /// clamped to the column's `min_width` and `max_width`, and
1341    /// [`TableEvent::ColumnWidthsChanged`] is emitted when it changed. Returns
1342    /// whether the delegate gave a width: `false` when the column cannot be
1343    /// resized or the delegate answered `None`.
1344    pub fn fit_col(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) -> bool {
1345        if !self.is_col_resizable(col_ix) {
1346            return false;
1347        }
1348        let Some(content) = self.delegate.fit_column(col_ix, window, cx) else {
1349            return false;
1350        };
1351        let padding = self
1352            .col_groups
1353            .get(col_ix)
1354            .and_then(|group| group.column.paddings)
1355            .unwrap_or_else(|| self.options.size.table_cell_padding());
1356        // Layout rounds a width to the nearest device pixel, and text even a
1357        // fraction of a pixel wider than its cell is truncated, so round every
1358        // part up to a whole device pixel.
1359        let scale_factor = window.scale_factor();
1360        let device_pixels = |length: Pixels| (f32::from(length) * scale_factor).ceil();
1361        let mut content_pixels = device_pixels(content);
1362        // Dividing back can land one ulp below the content at a fractional
1363        // scale, and the text is cut for that ulp too.
1364        if px(content_pixels / scale_factor) < content {
1365            content_pixels += 1.;
1366        }
1367        let width = content_pixels + device_pixels(padding.left) + device_pixels(padding.right);
1368        if self.resize_cols(col_ix, px(width / scale_factor), window, cx) {
1369            let new_widths = self.col_groups.iter().map(|g| g.width).collect();
1370            cx.emit(TableEvent::ColumnWidthsChanged(new_widths));
1371        }
1372        true
1373    }
1374
1375    /// The `ix`` is the index of the col to resize,
1376    /// and the `size` is the new size for the col.
1377    ///
1378    /// Returns whether the width changed.
1379    fn resize_cols(
1380        &mut self,
1381        ix: usize,
1382        size: Pixels,
1383        _: &mut Window,
1384        cx: &mut Context<Self>,
1385    ) -> bool {
1386        if !self.col_resizable {
1387            return false;
1388        }
1389
1390        let mut changed = false;
1391        if let Some(col_group) = self.col_groups.get_mut(ix) {
1392            if col_group.is_resizable() {
1393                let new_width = size
1394                    .max(col_group.column.min_width)
1395                    .min(col_group.column.max_width);
1396                if col_group.width != new_width {
1397                    col_group.width = new_width;
1398                    changed = true;
1399                }
1400            }
1401        }
1402
1403        if changed {
1404            self.update_header_layout(cx);
1405            cx.notify();
1406        }
1407        changed
1408    }
1409
1410    fn perform_sort(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
1411        if !self.sortable {
1412            return;
1413        }
1414
1415        let sort = self.col_groups.get(col_ix).and_then(|g| g.column.sort);
1416        if sort.is_none() {
1417            return;
1418        }
1419
1420        let sort = sort.unwrap();
1421        let sort = match sort {
1422            ColumnSort::Ascending => ColumnSort::Default,
1423            ColumnSort::Descending => ColumnSort::Ascending,
1424            ColumnSort::Default => ColumnSort::Descending,
1425        };
1426
1427        for (ix, col_group) in self.col_groups.iter_mut().enumerate() {
1428            if ix == col_ix {
1429                col_group.column.sort = Some(sort);
1430            } else {
1431                if col_group.column.sort.is_some() {
1432                    col_group.column.sort = Some(ColumnSort::Default);
1433                }
1434            }
1435        }
1436
1437        self.delegate_mut().perform_sort(col_ix, sort, window, cx);
1438
1439        cx.notify();
1440    }
1441
1442    fn move_column(
1443        &mut self,
1444        col_ix: usize,
1445        to_ix: usize,
1446        window: &mut Window,
1447        cx: &mut Context<Self>,
1448    ) {
1449        if col_ix == to_ix {
1450            return;
1451        }
1452
1453        self.delegate.move_column(col_ix, to_ix, window, cx);
1454        let col_group = self.col_groups.remove(col_ix);
1455        self.col_groups.insert(to_ix, col_group);
1456
1457        cx.emit(TableEvent::MoveColumn(col_ix, to_ix));
1458        cx.notify();
1459    }
1460
1461    /// Resolve the insertion gap for a column-header drag at the window
1462    /// coordinate `x`, or `None` when dropping there would not move the
1463    /// dragged column at `drag_col_ix`.
1464    fn drag_gap_at(&self, x: Pixels, drag_col_ix: usize) -> Option<usize> {
1465        let scrollable_cols = self.scrollable_cols();
1466
1467        // A column can only be reordered within its own region: rendering
1468        // pins the leading and trailing columns by count, so a cross-region
1469        // move would change which columns are pinned without updating their
1470        // `fixed` flags.
1471        let pointer_side = if scrollable_cols.start > 0 && x < self.fixed_head_cols_bounds.right() {
1472            Some(ColumnFixed::Left)
1473        } else if scrollable_cols.end < self.col_groups.len()
1474            && x >= self.fixed_right_head_cols_bounds.left()
1475        {
1476            Some(ColumnFixed::Right)
1477        } else {
1478            None
1479        };
1480        if self.col_fixed_side(drag_col_ix) != pointer_side {
1481            return None;
1482        }
1483
1484        // Columns scrolled beneath the fixed regions keep stale bounds, so
1485        // resolve `x` against the fixed columns alone when it falls in either
1486        // region, and against the visible scrollable columns otherwise.
1487        let candidates = match pointer_side {
1488            Some(ColumnFixed::Left) => 0..scrollable_cols.start,
1489            Some(ColumnFixed::Right) => scrollable_cols.end..self.col_groups.len(),
1490            None => self.calculate_visible_leaf_col_range(scrollable_cols).0,
1491        };
1492
1493        // The gap sits after the last candidate column whose center is left of `x`.
1494        let mut gap = candidates.start;
1495        for ix in candidates {
1496            if x < self.col_groups[ix].bounds.center().x {
1497                break;
1498            }
1499            gap = ix + 1;
1500        }
1501
1502        // No gap if dropping there would put the dragged column back to
1503        // where it already is.
1504        if gap == drag_col_ix || gap == drag_col_ix + 1 {
1505            None
1506        } else {
1507            Some(gap)
1508        }
1509    }
1510
1511    /// Dispatch delegate's `load_more` method when the visible range is near the end.
1512    fn load_more_if_need(
1513        &mut self,
1514        rows_count: usize,
1515        visible_end: usize,
1516        window: &mut Window,
1517        cx: &mut Context<Self>,
1518    ) {
1519        let threshold = self.delegate.load_more_threshold();
1520        // Securely handle subtract logic to prevent attempt to subtract with overflow
1521        if visible_end >= rows_count.saturating_sub(threshold) {
1522            if !self.delegate.has_more(cx) {
1523                return;
1524            }
1525
1526            self._load_more_task = cx.spawn_in(window, async move |view, window| {
1527                _ = view.update_in(window, |view, window, cx| {
1528                    view.delegate.load_more(window, cx);
1529                });
1530            });
1531        }
1532    }
1533
1534    fn update_visible_range_if_need(
1535        &mut self,
1536        visible_range: Range<usize>,
1537        items_count: usize,
1538        axis: Axis,
1539        window: &mut Window,
1540        cx: &mut Context<Self>,
1541    ) {
1542        // Skip when visible range is only 1 item, unless there is at most 1 item.
1543        // The visual_list will use first item to measure.
1544        if visible_range.len() <= 1 && items_count > 1 {
1545            return;
1546        }
1547
1548        // Stripe filler rows are rendered past the last row; never report them.
1549        let end = visible_range.end.min(items_count);
1550        let visible_range = visible_range.start.min(end)..end;
1551        // A range wholly past the last item is stale; the list scrolls back next frame.
1552        if visible_range.is_empty() && items_count > 0 {
1553            return;
1554        }
1555
1556        if axis == Axis::Vertical {
1557            if self.visible_range.rows == visible_range {
1558                return;
1559            }
1560            self.delegate_mut()
1561                .visible_rows_changed(visible_range.clone(), window, cx);
1562            self.visible_range.rows = visible_range;
1563        } else {
1564            if self.visible_range.cols == visible_range {
1565                return;
1566            }
1567            self.delegate_mut()
1568                .visible_columns_changed(visible_range.clone(), window, cx);
1569            self.visible_range.cols = visible_range;
1570        }
1571    }
1572
1573    fn render_cell(
1574        &self,
1575        _row_ix: Option<usize>,
1576        col_ix: usize,
1577        _window: &mut Window,
1578        cx: &mut Context<Self>,
1579    ) -> Div {
1580        let Some(col_group) = self.col_groups.get(col_ix) else {
1581            return div();
1582        };
1583        let is_rtl = gpui_base::LayoutDirection::global(cx).is_rtl();
1584
1585        let col_width = col_group.width;
1586        let col_padding = col_group.column.paddings;
1587
1588        div()
1589            .w(col_width)
1590            .h_full()
1591            .flex_shrink_0()
1592            .overflow_hidden()
1593            .whitespace_nowrap()
1594            .table_cell_size(self.options.size)
1595            // Text alignment is inherited, so this aligns the header name and
1596            // the delegate's cell text without changing how cells lay out.
1597            // `Left`/`Right` read as start/end, so they swap right to left.
1598            .map(|this| match (col_group.column.align, is_rtl) {
1599                (TextAlign::Center, _) => this.text_center(),
1600                (TextAlign::Right, false) | (TextAlign::Left, true) => this.text_right(),
1601                (TextAlign::Right, true) => this.text_left(),
1602                _ => this,
1603            })
1604            .map(|this| match col_padding {
1605                Some(padding) => this
1606                    .pl(padding.left)
1607                    .pr(padding.right)
1608                    .pt(padding.top)
1609                    .pb(padding.bottom),
1610                None => this,
1611            })
1612    }
1613
1614    /// Expose a body cell to assistive technology: its role, its column and
1615    /// the delegate's [`cell_label`](TableDelegate::cell_label).
1616    ///
1617    /// In cell selection mode the cell is a `GridCell` that reports whether it
1618    /// is selected; otherwise it is a plain `Cell`.
1619    fn a11y_cell<E>(&self, cell: E, row_ix: usize, col_ix: usize, window: &Window, cx: &App) -> E
1620    where
1621        E: gpui::StatefulInteractiveElement + FluentBuilder,
1622    {
1623        let cell = if self.cell_selectable {
1624            let is_selected = self.selected_cell() == Some((row_ix, col_ix));
1625            cell.role(gpui::Role::GridCell)
1626                .aria_selected(is_selected)
1627                // While the table has focus, the selected cell is the
1628                // focused node for assistive technology.
1629                .when(
1630                    is_selected && self.focus_handle.is_focused(window),
1631                    |this| this.aria_active_descendant(),
1632                )
1633        } else {
1634            cell.role(gpui::Role::Cell)
1635        };
1636        // Labels are only read through the accessibility tree, so skip
1637        // building them when no assistive technology is connected (tests
1638        // read them through test support).
1639        let label = if window.is_a11y_active() || cfg!(feature = "test-support") {
1640            self.delegate.cell_label(row_ix, col_ix, cx)
1641        } else {
1642            None
1643        };
1644        cell.aria_column_index(col_ix)
1645            .when_some(label, |this, label| this.aria_label(label))
1646    }
1647
1648    /// Show Column selection style, when the column is selected and the selection state is Column.
1649    /// Note: When a cell is selected, column selection style is not shown.
1650    fn render_col_wrap(
1651        &self,
1652        _row_ix: Option<usize>,
1653        col_ix: usize,
1654        _: &mut Window,
1655        cx: &mut Context<Self>,
1656    ) -> Div {
1657        let el = h_flex().h_full();
1658        let selectable = self.col_selectable
1659            && self
1660                .col_groups
1661                .get(col_ix)
1662                .map(|col_group| col_group.column.selectable)
1663                .unwrap_or(false);
1664
1665        // `selected_col()` is `None` outside column mode, so a selected cell
1666        // never leaves its column highlighted.
1667        if selectable && self.selected_col() == Some(col_ix) {
1668            el.bg(cx.theme().tokens.table_active)
1669        } else {
1670            el
1671        }
1672    }
1673
1674    /// The other half of that band, for the boundary on the *left* of column
1675    /// `ix` — the one owned by column `ix - 1`.
1676    ///
1677    /// It is positioned absolutely so that reaching back over the boundary
1678    /// costs the header row no width, and it paints after this column's own
1679    /// cell so that it, and not a column reorder, receives the drag.
1680    fn render_leading_resize_handle(
1681        &self,
1682        ix: usize,
1683        _: &mut Window,
1684        cx: &mut Context<Self>,
1685    ) -> impl IntoElement {
1686        // The first right-fixed column stays put while the column before it
1687        // resizes, so its edge would not follow the pointer; that column's
1688        // own handle remains.
1689        let is_fixed_right = |ix: usize| {
1690            self.col_fixed
1691                && self.col_groups.get(ix).and_then(|col| col.column.fixed)
1692                    == Some(ColumnFixed::Right)
1693        };
1694        let Some(prev) = ix.checked_sub(1).filter(|prev| {
1695            self.is_col_resizable(*prev) && (!is_fixed_right(ix) || is_fixed_right(*prev))
1696        }) else {
1697            return div().into_any_element();
1698        };
1699
1700        self.resize_handle_band(prev, ("resizable-handle-leading", ix).into(), cx)
1701            .absolute()
1702            .top_0()
1703            .left_0()
1704            .h_full()
1705            .w(HANDLE_PADDING)
1706            .into_any_element()
1707    }
1708
1709    /// The half of column `ix`'s resize handle that lies inside column `ix`,
1710    /// along with the hairline that marks the boundary.
1711    ///
1712    /// It is [`HANDLE_PADDING`] wide, like the half on the far side, so the
1713    /// grab area is symmetric about the boundary. The negative margin keeps
1714    /// the band's net contribution to the header row zero, and `justify_end`
1715    /// pins the hairline to the column edge.
1716    fn render_resize_handle(
1717        &self,
1718        ix: usize,
1719        _: &mut Window,
1720        cx: &mut Context<Self>,
1721    ) -> impl IntoElement {
1722        if !self.is_col_resizable(ix) {
1723            return div().into_any_element();
1724        }
1725
1726        let group_id = SharedString::from(format!("resizable-handle:{}", ix));
1727
1728        self.resize_handle_band(ix, ("resizable-handle", ix).into(), cx)
1729            .group(group_id.clone())
1730            .h_full()
1731            .w(HANDLE_PADDING)
1732            .ml(-HANDLE_PADDING)
1733            .justify_end()
1734            .items_center()
1735            .child(
1736                div()
1737                    .h_full()
1738                    .justify_center()
1739                    .bg(cx.theme().table_row_border)
1740                    .group_hover(&group_id, |this| this.bg(cx.theme().border).h_full())
1741                    .w(px(1.)),
1742            )
1743            .into_any_element()
1744    }
1745
1746    fn is_col_resizable(&self, ix: usize) -> bool {
1747        self.col_resizable
1748            && self
1749                .col_groups
1750                .get(ix)
1751                .map(|col| col.is_resizable())
1752                .unwrap_or(false)
1753    }
1754
1755    /// The interactive band that drags the boundary on the right of column
1756    /// `ix`, carrying no styling that places or paints it.
1757    ///
1758    /// Paint order decides which element is offered a drag first: later
1759    /// siblings win, and a header cell starts a column reorder. So a single
1760    /// band straddling the boundary would lose its outer half to the next
1761    /// column's cell. Each boundary is covered by two bands instead, one in
1762    /// the `th` on either side, each rendered after that `th`'s own cell and
1763    /// so above everything it overlaps.
1764    fn resize_handle_band(
1765        &self,
1766        ix: usize,
1767        id: ElementId,
1768        cx: &mut Context<Self>,
1769    ) -> Stateful<Div> {
1770        h_flex()
1771            .id(id)
1772            .occlude()
1773            .cursor_col_resize()
1774            .on_drag_move(
1775                cx.listener(move |view, e: &DragMoveEvent<ResizeColumn>, window, cx| {
1776                    match e.drag(cx) {
1777                        ResizeColumn((entity_id, ix)) => {
1778                            if cx.entity_id() != *entity_id {
1779                                return;
1780                            }
1781
1782                            // sync col widths into real widths
1783                            // TODO: Consider to remove this, this may not need now.
1784                            // for (_, col_group) in view.col_groups.iter_mut().enumerate() {
1785                            //     col_group.width = col_group.bounds.size.width;
1786                            // }
1787
1788                            let ix = *ix;
1789                            if view.fitted_col == Some(ix) {
1790                                return;
1791                            }
1792                            view.resizing_col = Some(ix);
1793
1794                            let col_group = view
1795                                .col_groups
1796                                .get(ix)
1797                                .expect("BUG: invalid col index")
1798                                .clone();
1799
1800                            // The width at the press, plus how far the pointer
1801                            // has moved since. The column's left edge isn't a
1802                            // fixed point: it moves when the table scrolls,
1803                            // and the scroll offset clamps as the columns
1804                            // narrow.
1805                            let Some(origin) = view.resize_origin else {
1806                                return;
1807                            };
1808                            view.resize_cols(
1809                                ix,
1810                                origin.width + (e.event.position.x - origin.x),
1811                                window,
1812                                cx,
1813                            );
1814
1815                            // scroll the table if the drag is near the edge
1816                            view.scroll_table_by_col_resizing(e.event.position, &col_group);
1817                        }
1818                    };
1819                }),
1820            )
1821            .on_drag(ResizeColumn((cx.entity_id(), ix)), |drag, _, _, cx| {
1822                cx.stop_propagation();
1823                cx.new(|_| drag.clone())
1824            })
1825            .on_mouse_down(
1826                MouseButton::Left,
1827                cx.listener(move |view, e: &MouseDownEvent, window, cx| {
1828                    view.resize_origin = view.col_groups.get(ix).map(|col_group| ResizeOrigin {
1829                        x: e.position.x,
1830                        width: col_group.width,
1831                    });
1832                    if e.click_count == 1 {
1833                        view.fitted_col = None;
1834                    } else if e.click_count == 2 && view.fit_col(ix, window, cx) {
1835                        view.fitted_col = Some(ix);
1836                    }
1837                }),
1838            )
1839            .on_mouse_up_out(
1840                MouseButton::Left,
1841                cx.listener(|view, _, _, cx| {
1842                    view.resize_origin = None;
1843                    if view.resizing_col.is_none() {
1844                        return;
1845                    }
1846
1847                    view.resizing_col = None;
1848
1849                    let new_widths = view.col_groups.iter().map(|g| g.width).collect();
1850                    cx.emit(TableEvent::ColumnWidthsChanged(new_widths));
1851                    cx.notify();
1852                }),
1853            )
1854    }
1855
1856    /// The border on the inner edge of the fixed columns pinned to `side`,
1857    /// unless turned off with [`DataTable::fixed_cols_border`].
1858    fn render_fixed_cols_border(&self, side: ColumnFixed, cx: &App) -> Option<Div> {
1859        self.options.fixed_cols_border.then(|| {
1860            div()
1861                .absolute()
1862                .top_0()
1863                .bottom_0()
1864                .w_0()
1865                .flex_shrink_0()
1866                .border_color(cx.theme().border)
1867                .map(|this| match side {
1868                    ColumnFixed::Left => this.right_0().border_r_1(),
1869                    ColumnFixed::Right => this.left_0().border_l_1(),
1870                })
1871        })
1872    }
1873
1874    /// Render the row header cell (when cell_selectable is enabled)
1875    fn render_row_header_cell(
1876        &self,
1877        row_ix: usize,
1878        is_head: bool,
1879        cx: &mut Context<Self>,
1880    ) -> impl IntoElement {
1881        div()
1882            .id(("row-header", row_ix))
1883            .w_3()
1884            .h_full()
1885            .border_r_1()
1886            .border_color(cx.theme().table_row_border)
1887            .bg(cx.theme().tokens.table_head)
1888            .flex_shrink_0()
1889            .table_cell_size(self.options.size)
1890            .when(!is_head, |this| {
1891                this.when(self.row_selectable, |this| {
1892                    this.on_click(cx.listener(move |table, e: &ClickEvent, _window, cx| {
1893                        cx.stop_propagation();
1894                        if table.selects_row_on_click(e, cx) {
1895                            table.select_row(row_ix, true, cx);
1896                        }
1897                    }))
1898                })
1899            })
1900    }
1901
1902    fn render_sort_icon(
1903        &self,
1904        col_ix: usize,
1905        col_group: &ColGroup,
1906        _: &mut Window,
1907        cx: &mut Context<Self>,
1908    ) -> Option<impl IntoElement> {
1909        if !self.sortable {
1910            return None;
1911        }
1912
1913        let Some(sort) = col_group.column.sort else {
1914            return None;
1915        };
1916
1917        let (icon, is_on) = match sort {
1918            ColumnSort::Ascending => (IconName::SortAscending, true),
1919            ColumnSort::Descending => (IconName::SortDescending, true),
1920            ColumnSort::Default => (IconName::ChevronsUpDown, false),
1921        };
1922
1923        Some(
1924            div()
1925                .id(("icon-sort", col_ix))
1926                .test_support()
1927                .role(gpui::Role::Button)
1928                .aria_label(t!("Table.SortBy", column = col_group.column.name).to_string())
1929                .p(px(2.))
1930                .rounded(cx.theme().radius / 2.)
1931                .map(|this| match is_on {
1932                    true => this,
1933                    false => this.opacity(0.5),
1934                })
1935                .hover(|this| this.bg(cx.theme().tokens.secondary).opacity(7.))
1936                .active(|this| this.bg(cx.theme().tokens.secondary_active).opacity(1.))
1937                .on_click(
1938                    cx.listener(move |table, _, window, cx| table.perform_sort(col_ix, window, cx)),
1939                )
1940                .child(
1941                    Icon::new(icon)
1942                        .size_3()
1943                        .text_color(cx.theme().secondary_foreground),
1944                ),
1945        )
1946    }
1947
1948    /// Render the column header.
1949    /// The children must be one by one items.
1950    /// Because the horizontal scroll handle will use the child_item_bounds to
1951    /// calculate the item position for itself's `scroll_to_item` method.
1952    fn render_th(&mut self, col_ix: usize, window: &mut Window, cx: &mut Context<Self>) -> Div {
1953        let entity_id = cx.entity_id();
1954        let col_group = self.col_groups.get(col_ix).expect("BUG: invalid col index");
1955
1956        let movable = self.col_movable && col_group.column.movable;
1957        let paddings = col_group.column.paddings;
1958        let name = col_group.column.name.clone();
1959
1960        h_flex()
1961            .h_full()
1962            .child(
1963                self.render_cell(None, col_ix, window, cx)
1964                    // A header given its own height may be shorter than a
1965                    // row, with no room for a row's padding above and below
1966                    // the name, so the name centres in it instead. A column's
1967                    // own paddings still apply.
1968                    .when(
1969                        self.options.header_row_height.is_some() && paddings.is_none(),
1970                        |this| this.py_0(),
1971                    )
1972                    .id(("col-header", col_ix))
1973                    .role(gpui::Role::ColumnHeader)
1974                    .aria_label(name.clone())
1975                    .aria_column_index(col_ix)
1976                    .test_support()
1977                    .on_click(cx.listener(move |this, _, window, cx| {
1978                        this.on_col_head_click(col_ix, window, cx);
1979                    }))
1980                    .child(
1981                        h_flex()
1982                            .size_full()
1983                            .justify_between()
1984                            .items_center()
1985                            .child(self.delegate.render_th(col_ix, window, cx))
1986                            .when_some(paddings, |this, paddings| {
1987                                // Leave right space for the sort icon, if this column have custom padding
1988                                let offset_pr =
1989                                    self.options.size.table_cell_padding().right - paddings.right;
1990                                this.pr(offset_pr.max(px(0.)))
1991                            })
1992                            .children(self.render_sort_icon(col_ix, &col_group, window, cx)),
1993                    )
1994                    .when(movable, |this| {
1995                        this.on_drag(
1996                            DragColumn {
1997                                entity_id,
1998                                col_ix,
1999                                name,
2000                                width: col_group.width,
2001                            },
2002                            |drag, _, _, cx| {
2003                                cx.stop_propagation();
2004                                cx.new(|_| drag.clone())
2005                            },
2006                        )
2007                    })
2008                    .map(|this| {
2009                        // Draw the insertion indicator on the left edge of the gap
2010                        // column, or on the right edge of the last column for the
2011                        // trailing gap. Use an absolutely positioned overlay instead
2012                        // of a border, to avoid shifting the cell content.
2013                        let last_gap = col_ix + 1 == self.col_groups.len();
2014                        match self.col_drag_gap {
2015                            Some(gap)
2016                                if cx.has_active_drag()
2017                                    && (gap == col_ix || (last_gap && gap == col_ix + 1)) =>
2018                            {
2019                                let right_side = gap == col_ix + 1;
2020                                this.relative().child(
2021                                    div()
2022                                        .absolute()
2023                                        .top_0()
2024                                        .bottom_0()
2025                                        .w(px(2.))
2026                                        .map(|d| if right_side { d.right_0() } else { d.left_0() })
2027                                        .bg(cx.theme().drag_border),
2028                                )
2029                            }
2030                            _ => this,
2031                        }
2032                    }),
2033            )
2034            // resize handle cell right side
2035            .child(self.render_resize_handle(col_ix, window, cx))
2036            // resize handle cell left side
2037            .child(self.render_leading_resize_handle(col_ix, window, cx))
2038            // to save the bounds of this col.
2039            .on_prepaint({
2040                let view = cx.entity();
2041                move |bounds, _, cx| view.update(cx, |r, _| r.col_groups[col_ix].bounds = bounds)
2042            })
2043    }
2044
2045    /// Compute the visible non-fixed leaf-column range for header rendering.
2046    ///
2047    /// Returns `(visible_range, left_spacer_width)` where:
2048    /// - `visible_range` is the column-index range that should be rendered.
2049    /// - `left_spacer_width` is the total width of the off-screen left columns,
2050    ///   used as a spacer div to keep visible columns at the correct position.
2051    ///
2052    /// On the first frame `self.bounds` is zero, so a fallback that covers all
2053    /// columns is returned to avoid a blank header on initial paint.
2054    fn calculate_visible_leaf_col_range(
2055        &self,
2056        scrollable_cols: Range<usize>,
2057    ) -> (Range<usize>, Pixels) {
2058        let (left_columns_count, total_cols) = (scrollable_cols.start, scrollable_cols.end);
2059
2060        if self.bounds.size.width == px(0.) {
2061            return (scrollable_cols, px(0.));
2062        }
2063
2064        let fixed_width =
2065            self.fixed_head_cols_bounds.size.width + self.fixed_right_head_cols_bounds.size.width;
2066        let available_width = (self.bounds.size.width - fixed_width).max(px(0.));
2067        // The scroll handle offset is negative when scrolled right; negate it
2068        // to obtain a positive distance from the left edge of the scroll area.
2069        let scroll_x = (-self.horizontal_scroll_handle.offset().x).max(px(0.));
2070
2071        // Walk left-to-right through non-fixed columns to find the first one
2072        // whose right edge enters the viewport. The accumulated width of the
2073        // skipped columns becomes the left spacer width.
2074        let mut range_start = left_columns_count;
2075        let mut left_spacer = px(0.);
2076        let mut cumulative = px(0.);
2077        for i in left_columns_count..total_cols {
2078            let right_edge = cumulative + self.col_groups[i].width;
2079            if right_edge > scroll_x {
2080                range_start = i;
2081                left_spacer = cumulative;
2082                break;
2083            }
2084            cumulative = right_edge;
2085        }
2086
2087        // Continue from `range_start` (skipping already-scanned columns) to
2088        // find the last column still within the viewport. The 200 px overdraw
2089        // buffer prevents a visible flash when the user scrolls quickly.
2090        let right_bound = scroll_x + available_width + px(200.);
2091        let mut range_end = total_cols;
2092        let mut cumulative = left_spacer; // already summed widths before `range_start`
2093        for i in range_start..total_cols {
2094            cumulative += self.col_groups[i].width;
2095            if cumulative > right_bound {
2096                range_end = (i + 1).min(total_cols);
2097                break;
2098            }
2099        }
2100
2101        (range_start..range_end, left_spacer)
2102    }
2103
2104    fn render_table_header(
2105        &mut self,
2106        scrollable_cols: Range<usize>,
2107        window: &mut Window,
2108        cx: &mut Context<Self>,
2109    ) -> impl IntoElement {
2110        let horizontal_scroll_handle = self.horizontal_scroll_handle.clone();
2111
2112        // Header leaf-column virtualization.
2113        //
2114        // `render_th` creates interactive elements with resize-handle listeners.
2115        // Calling it for every column every frame is O(n) in column count; with
2116        // 1000+ columns this alone drops FPS below 60 even in release mode.
2117        //
2118        // We restrict rendering to the columns currently visible inside the
2119        // overflow-scroll viewport, surrounding them with inert spacer divs:
2120        //
2121        //   [left_spacer] [visible columns…] [right_spacer] [last_empty_col]
2122        //
2123        // The spacers preserve the flex container's total content width so that
2124        // the scrollbar range stays correct.
2125        let total_cols = self.col_groups.len();
2126        let left_columns_count = scrollable_cols.start;
2127        let right_columns_start = scrollable_cols.end;
2128        let (visible_col_range, left_spacer) =
2129            self.calculate_visible_leaf_col_range(scrollable_cols.clone());
2130
2131        let layout_len = self.header_layout.len();
2132        let header_row_height = self.header_row_height();
2133
2134        // Reset fixed head columns bounds, if no fixed columns are present
2135        if left_columns_count == 0 {
2136            self.fixed_head_cols_bounds = Bounds::default();
2137        }
2138        if right_columns_start == total_cols {
2139            self.fixed_right_head_cols_bounds = Bounds::default();
2140        }
2141
2142        let mut header = self.delegate_mut().render_header(window, cx);
2143        let style = header.style().clone();
2144        let layout = self.header_layout.clone();
2145
2146        header
2147            // One header row holds every column header, including the pinned
2148            // ones, which are laid out in a separate container.
2149            .role(gpui::Role::Row)
2150            .aria_row_index(0)
2151            .h_flex()
2152            .w_full()
2153            .flex_shrink_0()
2154            .bg(cx.theme().tokens.table_head)
2155            .text_color(cx.theme().table_head_foreground)
2156            .refine_style(&style)
2157            .on_drag_move(cx.listener(|table, e: &DragMoveEvent<DragColumn>, _, cx| {
2158                let drag = e.drag(cx);
2159                let (drag_entity_id, drag_col_ix) = (drag.entity_id, drag.col_ix);
2160
2161                let gap =
2162                    if drag_entity_id == cx.entity_id() && e.bounds.contains(&e.event.position) {
2163                        table.drag_gap_at(e.event.position.x, drag_col_ix)
2164                    } else {
2165                        None
2166                    };
2167
2168                if table.col_drag_gap != gap {
2169                    table.col_drag_gap = gap;
2170                    cx.notify();
2171                }
2172            }))
2173            .on_drop(cx.listener(|table, drag: &DragColumn, window, cx| {
2174                if drag.entity_id != cx.entity_id() {
2175                    return;
2176                }
2177
2178                // Insert the dragged column into the indicated gap.
2179                let Some(gap) = table.col_drag_gap.take() else {
2180                    return;
2181                };
2182                let to_ix = if drag.col_ix < gap { gap - 1 } else { gap };
2183                table.move_column(drag.col_ix, to_ix, window, cx);
2184            }))
2185            .when(self.cell_selectable && self.row_header, |this| {
2186                this.child(self.render_row_header_cell(0, true, cx))
2187            })
2188            .when(left_columns_count > 0, |this| {
2189                this.child(self.render_fixed_head_cols(
2190                    0..left_columns_count,
2191                    ColumnFixed::Left,
2192                    window,
2193                    cx,
2194                ))
2195            })
2196            .child(
2197                // Columns
2198                h_flex()
2199                    .id("table-head")
2200                    .size_full()
2201                    .overflow_scroll()
2202                    .relative()
2203                    .track_scroll(&horizontal_scroll_handle)
2204                    .bg(cx.theme().tokens.table_head)
2205                    .child(v_flex().min_w_full().flex_shrink_0().children(
2206                        layout.iter().enumerate().map(|(row_ix, row_cells)| {
2207                            let is_leaf_row = row_ix + 1 == layout_len;
2208                            h_flex()
2209                                .min_w_full()
2210                                .h(header_row_height)
2211                                .border_b_1()
2212                                .border_color(cx.theme().border)
2213                                .map(|this| {
2214                                    if is_leaf_row {
2215                                        // Leaf row: apply the spacer virtualization pattern.
2216                                        // Only columns in `visible_range` are rendered; the two
2217                                        // spacer divs preserve the container's total content width
2218                                        // so the scrollbar range stays correct.
2219                                        this.when(left_spacer > px(0.), |r| {
2220                                            r.child(div().w(left_spacer).h_full().flex_shrink_0())
2221                                        })
2222                                        .children(row_cells.iter().filter_map(|cell| {
2223                                            if cell.is_leaf {
2224                                                let ix = cell.leaf_col_ix?;
2225                                                if !visible_col_range.contains(&ix) {
2226                                                    return None;
2227                                                }
2228                                                Some(
2229                                                    self.render_th(ix, window, cx)
2230                                                        .into_any_element(),
2231                                                )
2232                                            } else {
2233                                                None
2234                                            }
2235                                        }))
2236                                        .when(visible_col_range.end < right_columns_start, |r| {
2237                                            let right_spacer: Pixels = self.col_groups
2238                                                [visible_col_range.end..right_columns_start]
2239                                                .iter()
2240                                                .map(|g| g.width)
2241                                                .sum();
2242                                            r.child(div().w(right_spacer).h_full().flex_shrink_0())
2243                                        })
2244                                        .child(self.delegate.render_last_empty_col(window, cx))
2245                                    } else {
2246                                        // Group header rows have far fewer cells (one per group),
2247                                        // so the cost of rendering all of them is negligible.
2248                                        this.children(row_cells.iter().filter_map(|cell| {
2249                                            if scrollable_cols.contains(&cell.start_leaf_col_ix) {
2250                                                if cell.is_leaf {
2251                                                    if let Some(ix) = cell.leaf_col_ix {
2252                                                        return Some(
2253                                                            self.render_th(ix, window, cx)
2254                                                                .into_any_element(),
2255                                                        );
2256                                                    }
2257                                                } else {
2258                                                    return Some(
2259                                                        self.delegate_mut()
2260                                                            .render_group_th(
2261                                                                &cell.label,
2262                                                                cell.col_span,
2263                                                                cell.width,
2264                                                                window,
2265                                                                cx,
2266                                                            )
2267                                                            .into_any_element(),
2268                                                    );
2269                                                }
2270                                            }
2271                                            None
2272                                        }))
2273                                        .child(self.delegate.render_last_empty_col(window, cx))
2274                                    }
2275                                })
2276                        }),
2277                    )),
2278            )
2279            .when(right_columns_start < total_cols, |this| {
2280                this.child(self.render_fixed_head_cols(
2281                    right_columns_start..total_cols,
2282                    ColumnFixed::Right,
2283                    window,
2284                    cx,
2285                ))
2286            })
2287    }
2288
2289    /// Render the header cells of the fixed columns `cols` pinned to `side`,
2290    /// including group header cells that start in `cols`.
2291    fn render_fixed_head_cols(
2292        &mut self,
2293        cols: Range<usize>,
2294        side: ColumnFixed,
2295        window: &mut Window,
2296        cx: &mut Context<Self>,
2297    ) -> impl IntoElement {
2298        let view = cx.entity();
2299        let header_row_height = self.header_row_height();
2300        let layout = self.header_layout.clone();
2301
2302        h_flex()
2303            .relative()
2304            .h_full()
2305            .flex_shrink_0()
2306            .bg(cx.theme().tokens.table_head)
2307            .child(
2308                v_flex()
2309                    .min_w_full()
2310                    .flex_shrink_0()
2311                    .children(layout.iter().map(|row_cells| {
2312                        h_flex()
2313                            .min_w_full()
2314                            .h(header_row_height)
2315                            .border_b_1()
2316                            .border_color(cx.theme().border)
2317                            .children(row_cells.iter().filter_map(|cell| {
2318                                if !cols.contains(&cell.start_leaf_col_ix) {
2319                                    return None;
2320                                }
2321
2322                                if cell.is_leaf {
2323                                    let ix = cell.leaf_col_ix?;
2324                                    Some(self.render_th(ix, window, cx).into_any_element())
2325                                } else {
2326                                    Some(
2327                                        self.delegate_mut()
2328                                            .render_group_th(
2329                                                &cell.label,
2330                                                cell.col_span,
2331                                                cell.width,
2332                                                window,
2333                                                cx,
2334                                            )
2335                                            .into_any_element(),
2336                                    )
2337                                }
2338                            }))
2339                    })),
2340            )
2341            .children(self.render_fixed_cols_border(side, cx))
2342            .on_prepaint(move |bounds, _, cx| {
2343                view.update(cx, |table, _| match side {
2344                    ColumnFixed::Left => table.fixed_head_cols_bounds = bounds,
2345                    ColumnFixed::Right => table.fixed_right_head_cols_bounds = bounds,
2346                })
2347            })
2348    }
2349
2350    #[allow(clippy::too_many_arguments)]
2351    fn render_table_row(
2352        &mut self,
2353        row_ix: usize,
2354        rows_count: usize,
2355        scrollable_cols: Range<usize>,
2356        col_sizes: Rc<Vec<gpui::Size<Pixels>>>,
2357        columns_count: usize,
2358        is_filled: bool,
2359        window: &mut Window,
2360        cx: &mut Context<Self>,
2361    ) -> gpui::AnyElement {
2362        let is_stripe_row = self.options.stripe && row_ix % 2 != 0;
2363        // `selected_row()` is `None` outside row mode, so a selected cell or
2364        // column never highlights its row.
2365        let is_selected = self.selected_row() == Some(row_ix);
2366        let view = cx.entity();
2367        let row_height = self.options.size.table_row_height();
2368
2369        if row_ix < rows_count {
2370            let is_last_row = row_ix + 1 == rows_count;
2371            let need_render_border = is_selected || !is_last_row || !is_filled;
2372
2373            let mut tr = self.delegate.render_tr(row_ix, window, cx);
2374            let style = tr.style().clone();
2375            // As with cell labels, only build the name when it can be read.
2376            let label = if window.is_a11y_active() || cfg!(feature = "test-support") {
2377                self.delegate.row_label(row_ix, cx)
2378            } else {
2379                None
2380            };
2381
2382            tr.test_support()
2383                .role(gpui::Role::Row)
2384                // Row 0 is the header row.
2385                .aria_row_index(row_ix + 1)
2386                .when_some(label, |this, label| this.aria_label(label))
2387                .aria_selected(is_selected)
2388                // While the table has focus, the selected row is the focused
2389                // node for assistive technology.
2390                .when(
2391                    is_selected && self.focus_handle.is_focused(window),
2392                    |this| this.aria_active_descendant(),
2393                )
2394                .h_flex()
2395                .w_full()
2396                .h(row_height)
2397                .when(need_render_border, |this| {
2398                    this.border_b_1().border_color(cx.theme().table_row_border)
2399                })
2400                .when(is_stripe_row, |this| this.bg(cx.theme().tokens.table_even))
2401                .refine_style(&style)
2402                .hover(|this| {
2403                    if is_selected || self.right_clicked_row == Some(row_ix) {
2404                        this
2405                    } else {
2406                        this.bg(cx.theme().tokens.table_hover)
2407                    }
2408                })
2409                .when(self.cell_selectable && self.row_header, |this| {
2410                    this.child(self.render_row_header_cell(row_ix, false, cx))
2411                })
2412                .when(scrollable_cols.start > 0, |this| {
2413                    this.child(self.render_fixed_cells(
2414                        row_ix,
2415                        0..scrollable_cols.start,
2416                        ColumnFixed::Left,
2417                        window,
2418                        cx,
2419                    ))
2420                })
2421                .child(
2422                    h_flex()
2423                        .flex_1()
2424                        .h_full()
2425                        .overflow_hidden()
2426                        .relative()
2427                        .child(
2428                            crate::virtual_list::virtual_list(
2429                                view,
2430                                row_ix,
2431                                Axis::Horizontal,
2432                                col_sizes,
2433                                {
2434                                    let scrollable_cols = scrollable_cols.clone();
2435                                    move |table, visible_range: Range<usize>, window, cx| {
2436                                        table.update_visible_range_if_need(
2437                                            visible_range.clone(),
2438                                            scrollable_cols.len(),
2439                                            Axis::Horizontal,
2440                                            window,
2441                                            cx,
2442                                        );
2443
2444                                        let mut items = Vec::with_capacity(
2445                                            visible_range.end - visible_range.start,
2446                                        );
2447
2448                                        visible_range.for_each(|col_ix| {
2449                                            let col_ix = col_ix + scrollable_cols.start;
2450                                            let is_cell_selected =
2451                                                table.selected_cell() == Some((row_ix, col_ix));
2452                                            let is_cell_right_clicked =
2453                                                table.right_clicked_cell == Some((row_ix, col_ix));
2454
2455                                            let el = table
2456                                                .render_col_wrap(Some(row_ix), col_ix, window, cx)
2457                                                .child(
2458                                                    table
2459                                                        .a11y_cell(
2460                                                            table
2461                                                                .render_cell(
2462                                                                    Some(row_ix),
2463                                                                    col_ix,
2464                                                                    window,
2465                                                                    cx,
2466                                                                )
2467                                                                .id(format!(
2468                                                                    "table-cell-{}:{}",
2469                                                                    row_ix, col_ix
2470                                                                ))
2471                                                                .test_support(),
2472                                                            row_ix,
2473                                                            col_ix,
2474                                                            window,
2475                                                            cx,
2476                                                        )
2477                                                        .relative()
2478                                                        .child(table.measure_render_td(
2479                                                            row_ix, col_ix, window, cx,
2480                                                        ))
2481                                                        .when(is_cell_selected, |this| {
2482                                                            this.child(
2483                                                                div()
2484                                                                    .absolute()
2485                                                                    .inset_0()
2486                                                                    .bg(cx
2487                                                                        .theme()
2488                                                                        .tokens
2489                                                                        .table_active)
2490                                                                    .border_1()
2491                                                                    .border_color(
2492                                                                        cx.theme()
2493                                                                            .table_active_border,
2494                                                                    ),
2495                                                            )
2496                                                        })
2497                                                        .when(
2498                                                            is_cell_right_clicked
2499                                                                && !is_cell_selected,
2500                                                            |this| {
2501                                                                this.child(
2502                                                                    div()
2503                                                                        .absolute()
2504                                                                        .inset_0()
2505                                                                        .border_1()
2506                                                                        .border_color(
2507                                                                            cx.theme()
2508                                                                                .table_active_border
2509                                                                                .opacity(0.5),
2510                                                                        ),
2511                                                                )
2512                                                            },
2513                                                        )
2514                                                        .when(table.cell_selectable, |this| {
2515                                                            this.on_click(cx.listener(
2516                                                                move |table, e, window, cx| {
2517                                                                    cx.stop_propagation();
2518                                                                    table.on_cell_click(
2519                                                                        e, row_ix, col_ix, window,
2520                                                                        cx,
2521                                                                    );
2522                                                                },
2523                                                            ))
2524                                                            .on_mouse_down(
2525                                                                MouseButton::Right,
2526                                                                cx.listener(
2527                                                                    move |table, e, window, cx| {
2528                                                                        table.on_cell_right_click(
2529                                                                            e, row_ix, col_ix,
2530                                                                            window, cx,
2531                                                                        );
2532                                                                    },
2533                                                                ),
2534                                                            )
2535                                                        }),
2536                                                );
2537
2538                                            items.push(el);
2539                                        });
2540
2541                                        items
2542                                    }
2543                                },
2544                            )
2545                            .with_scroll_handle(&self.horizontal_scroll_handle),
2546                        )
2547                        .child(self.delegate.render_last_empty_col(window, cx)),
2548                )
2549                .when(scrollable_cols.end < self.col_groups.len(), |this| {
2550                    this.child(self.render_fixed_cells(
2551                        row_ix,
2552                        scrollable_cols.end..self.col_groups.len(),
2553                        ColumnFixed::Right,
2554                        window,
2555                        cx,
2556                    ))
2557                })
2558                // Row selected style
2559                .when(is_selected, |this| {
2560                    let bg = if cx.theme().list.active_highlight {
2561                        cx.theme().tokens.table_active
2562                    } else {
2563                        cx.theme().tokens.accent
2564                    };
2565                    this.bg(bg)
2566                })
2567                // Row right click row style
2568                .when(self.right_clicked_row == Some(row_ix), |this| {
2569                    this.border_color(gpui::transparent_white()).child(
2570                        div()
2571                            .top(if row_ix == 0 { px(0.) } else { px(-1.) })
2572                            .left(px(0.))
2573                            .right(px(0.))
2574                            .bottom(px(-1.))
2575                            .absolute()
2576                            .border_1()
2577                            .border_color(cx.theme().selection),
2578                    )
2579                })
2580                .on_mouse_down(
2581                    MouseButton::Right,
2582                    cx.listener(move |this, e, window, cx| {
2583                        this.on_row_right_click(e, Some(row_ix), window, cx);
2584                    }),
2585                )
2586                .on_click(cx.listener(move |this, e, window, cx| {
2587                    this.on_row_left_click(e, row_ix, window, cx);
2588                }))
2589                .into_any_element()
2590        } else {
2591            let cols_width: Pixels = self
2592                .col_groups
2593                .iter()
2594                .take(columns_count)
2595                .map(|col_group| col_group.width)
2596                .sum();
2597
2598            // Render fake rows to fill the rest table space
2599            self.delegate
2600                .render_tr(row_ix, window, cx)
2601                .h_flex()
2602                .w_full()
2603                .h(row_height)
2604                .border_b_1()
2605                .border_color(cx.theme().table_row_border)
2606                .when(is_stripe_row, |this| this.bg(cx.theme().tokens.table_even))
2607                .when(self.cell_selectable && self.row_header, |this| {
2608                    // Render empty row header cell for fake rows
2609                    this.child(
2610                        div()
2611                            .w(px(40.))
2612                            .h_full()
2613                            .flex_shrink_0()
2614                            .table_cell_size(self.options.size),
2615                    )
2616                })
2617                // The fake cells paint nothing, so a single spacer as wide as all
2618                // the columns keeps the last empty column in place without laying
2619                // out one element per column.
2620                .child(div().flex_shrink_0().h_full().w(cols_width))
2621                .child(self.delegate.render_last_empty_col(window, cx))
2622                .into_any_element()
2623        }
2624    }
2625
2626    /// Render the body cells of the fixed columns `cols` pinned to `side`.
2627    fn render_fixed_cells(
2628        &mut self,
2629        row_ix: usize,
2630        cols: Range<usize>,
2631        side: ColumnFixed,
2632        window: &mut Window,
2633        cx: &mut Context<Self>,
2634    ) -> impl IntoElement {
2635        let items: Vec<_> = cols
2636            .map(|col_ix| {
2637                let is_cell_selected = self.selected_cell() == Some((row_ix, col_ix));
2638                let is_cell_right_clicked = self.right_clicked_cell == Some((row_ix, col_ix));
2639
2640                self.render_col_wrap(Some(row_ix), col_ix, window, cx)
2641                    .child(
2642                        self.a11y_cell(
2643                            self.render_cell(Some(row_ix), col_ix, window, cx)
2644                                .id(format!("table-cell:{}:{}", row_ix, col_ix))
2645                                .test_support(),
2646                            row_ix,
2647                            col_ix,
2648                            window,
2649                            cx,
2650                        )
2651                        .relative()
2652                        .child(self.measure_render_td(row_ix, col_ix, window, cx))
2653                        .when(is_cell_selected, |this| {
2654                            this.child(
2655                                div()
2656                                    .absolute()
2657                                    .inset_0()
2658                                    .bg(cx.theme().tokens.table_active)
2659                                    .border_1()
2660                                    .border_color(cx.theme().table_active_border),
2661                            )
2662                        })
2663                        .when(is_cell_right_clicked && !is_cell_selected, |this| {
2664                            this.child(
2665                                div()
2666                                    .absolute()
2667                                    .inset_0()
2668                                    .border_1()
2669                                    .border_color(cx.theme().table_active_border.opacity(0.5)),
2670                            )
2671                        })
2672                        .when(self.cell_selectable, |this| {
2673                            this.on_click(cx.listener(move |table, e, window, cx| {
2674                                table.on_cell_click(e, row_ix, col_ix, window, cx);
2675                            }))
2676                            .on_mouse_down(
2677                                MouseButton::Right,
2678                                cx.listener(move |table, e, window, cx| {
2679                                    table.on_cell_right_click(e, row_ix, col_ix, window, cx);
2680                                }),
2681                            )
2682                        }),
2683                    )
2684            })
2685            .collect();
2686
2687        h_flex()
2688            .relative()
2689            .h_full()
2690            .flex_shrink_0()
2691            .children(items)
2692            .children(self.render_fixed_cols_border(side, cx))
2693    }
2694
2695    /// Calculate the extra rows needed to fill the table empty space when `stripe` is true.
2696    fn calculate_extra_rows_needed(
2697        &self,
2698        total_height: Pixels,
2699        actual_height: Pixels,
2700        row_height: Pixels,
2701    ) -> usize {
2702        let mut extra_rows_needed = 0;
2703
2704        let remaining_height = total_height - actual_height;
2705        if remaining_height > px(0.) {
2706            extra_rows_needed = (remaining_height / row_height).floor() as usize;
2707        }
2708
2709        extra_rows_needed
2710    }
2711
2712    #[inline]
2713    fn measure_render_td(
2714        &mut self,
2715        row_ix: usize,
2716        col_ix: usize,
2717        window: &mut Window,
2718        cx: &mut Context<Self>,
2719    ) -> impl IntoElement {
2720        if !crate::measure_enable() {
2721            return self
2722                .delegate
2723                .render_td(row_ix, col_ix, window, cx)
2724                .into_any_element();
2725        }
2726
2727        let start = std::time::Instant::now();
2728        let el = self.delegate.render_td(row_ix, col_ix, window, cx);
2729        self._measure.push(start.elapsed());
2730        el.into_any_element()
2731    }
2732
2733    fn measure(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
2734        if !crate::measure_enable() {
2735            return;
2736        }
2737
2738        // Print avg measure time of each td
2739        if self._measure.len() > 0 {
2740            let total = self
2741                ._measure
2742                .iter()
2743                .fold(Duration::default(), |acc, d| acc + *d);
2744            let avg = total / self._measure.len() as u32;
2745            eprintln!(
2746                "last render {} cells total: {:?}, avg: {:?}",
2747                self._measure.len(),
2748                total,
2749                avg,
2750            );
2751        }
2752        self._measure.clear();
2753    }
2754
2755    fn render_vertical_scrollbar(
2756        &mut self,
2757        _: &mut Window,
2758        _: &mut Context<Self>,
2759    ) -> Option<impl IntoElement> {
2760        Some(
2761            div()
2762                .absolute()
2763                .top(self.header_band_height())
2764                .right_0()
2765                .bottom_0()
2766                .w(Scrollbar::width())
2767                .child(
2768                    Scrollbar::vertical(&self.vertical_scroll_handle)
2769                        .viewport_from_layout()
2770                        .when_some(self.options.scrollbar_mode, |this, mode| this.mode(mode))
2771                        .max_fps(60),
2772                ),
2773        )
2774    }
2775
2776    fn render_horizontal_scrollbar(
2777        &mut self,
2778        _: &mut Window,
2779        _: &mut Context<Self>,
2780    ) -> impl IntoElement {
2781        div()
2782            .absolute()
2783            .left(self.fixed_head_cols_bounds.size.width)
2784            .right(self.fixed_right_head_cols_bounds.size.width)
2785            .bottom_0()
2786            .h(Scrollbar::width())
2787            .child(
2788                Scrollbar::horizontal(&self.horizontal_scroll_handle)
2789                    .viewport_from_layout()
2790                    .when_some(self.options.scrollbar_mode, |this, mode| this.mode(mode)),
2791            )
2792    }
2793}
2794
2795impl<D> Focusable for TableState<D>
2796where
2797    D: TableDelegate,
2798{
2799    fn focus_handle(&self, _cx: &gpui::App) -> FocusHandle {
2800        self.focus_handle.clone()
2801    }
2802}
2803impl<D> EventEmitter<TableEvent> for TableState<D> where D: TableDelegate {}
2804
2805impl<D> Render for TableState<D>
2806where
2807    D: TableDelegate,
2808{
2809    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2810        self.measure(window, cx);
2811
2812        let columns_count = self.delegate.columns_count(cx);
2813        let scrollable_cols = self.scrollable_cols();
2814        let rows_count = self.delegate.rows_count(cx);
2815        let loading = self.delegate.loading(cx);
2816
2817        let row_height = self.options.size.table_row_height();
2818        let total_height = self
2819            .vertical_scroll_handle
2820            .0
2821            .borrow()
2822            .base_handle
2823            .bounds()
2824            .size
2825            .height;
2826        let actual_height = row_height * rows_count as f32;
2827        let extra_rows_count =
2828            self.calculate_extra_rows_needed(total_height, actual_height, row_height);
2829        let render_rows_count = if self.options.stripe {
2830            rows_count + extra_rows_count
2831        } else {
2832            rows_count
2833        };
2834        let has_right_click = self.right_clicked_row.is_some() || self.right_clicked_cell.is_some();
2835        let is_filled = total_height > Pixels::ZERO && total_height <= actual_height;
2836
2837        let loading_view = if loading {
2838            Some(
2839                self.delegate
2840                    .render_loading(self.options.size, window, cx)
2841                    .into_any_element(),
2842            )
2843        } else {
2844            None
2845        };
2846
2847        let empty_view = if rows_count == 0 {
2848            // The rows list is not rendered, so report the empty range here.
2849            self.update_visible_range_if_need(0..0, 0, Axis::Vertical, window, cx);
2850            Some(
2851                div()
2852                    .size_full()
2853                    .child(self.delegate.render_empty(window, cx))
2854                    .into_any_element(),
2855            )
2856        } else {
2857            None
2858        };
2859
2860        let inner_table = v_flex()
2861            .id("table-inner")
2862            .test_support()
2863            .size_full()
2864            .overflow_hidden()
2865            .child(self.render_table_header(scrollable_cols.clone(), window, cx))
2866            .context_menu({
2867                let view = cx.entity();
2868                move |this, window: &mut Window, cx: &mut Context<PopupMenu>| {
2869                    if let Some(row_ix) = view.read(cx).right_clicked_row {
2870                        view.update(cx, |menu, cx| {
2871                            menu.delegate_mut().context_menu(row_ix, this, window, cx)
2872                        })
2873                    } else {
2874                        this
2875                    }
2876                }
2877            })
2878            .map(|this| {
2879                if rows_count == 0 {
2880                    this.children(empty_view)
2881                } else {
2882                    this.child(
2883                        h_flex().id("table-body").flex_grow_1().size_full().child(
2884                            uniform_list(
2885                                "table-uniform-list",
2886                                render_rows_count,
2887                                cx.processor(
2888                                    move |table, visible_range: Range<usize>, window, cx| {
2889                                        // Use `col.width` (always up-to-date) rather than
2890                                        // `col.bounds.size.width`, which is only set after
2891                                        // prepaint and is therefore zero on the first frame.
2892                                        let col_sizes: Rc<Vec<gpui::Size<Pixels>>> = Rc::new(
2893                                            table
2894                                                .col_groups
2895                                                .get(scrollable_cols.clone())
2896                                                .unwrap_or_default()
2897                                                .iter()
2898                                                .map(|col| gpui::Size {
2899                                                    width: col.width,
2900                                                    height: px(0.),
2901                                                })
2902                                                .collect(),
2903                                        );
2904
2905                                        table.load_more_if_need(
2906                                            rows_count,
2907                                            visible_range.end,
2908                                            window,
2909                                            cx,
2910                                        );
2911                                        table.update_visible_range_if_need(
2912                                            visible_range.clone(),
2913                                            rows_count,
2914                                            Axis::Vertical,
2915                                            window,
2916                                            cx,
2917                                        );
2918
2919                                        if visible_range.start >= rows_count {
2920                                            table.scroll_to_row(rows_count.saturating_sub(1), cx);
2921                                        }
2922
2923                                        let mut items = Vec::with_capacity(
2924                                            visible_range.end.saturating_sub(visible_range.start),
2925                                        );
2926
2927                                        // Render fake rows to fill the table
2928                                        visible_range.for_each(|row_ix| {
2929                                            // Render real rows for available data
2930                                            items.push(table.render_table_row(
2931                                                row_ix,
2932                                                rows_count,
2933                                                scrollable_cols.clone(),
2934                                                col_sizes.clone(),
2935                                                columns_count,
2936                                                is_filled,
2937                                                window,
2938                                                cx,
2939                                            ));
2940                                        });
2941
2942                                        items
2943                                    },
2944                                ),
2945                            )
2946                            .flex_grow_1()
2947                            .size_full()
2948                            .with_sizing_behavior(ListSizingBehavior::Auto)
2949                            .track_scroll(&self.vertical_scroll_handle)
2950                            .map(|rows| {
2951                                gpui_base::ScrollBounce::new(
2952                                    "table-scroll-bounce",
2953                                    &self.vertical_scroll_handle,
2954                                    rows,
2955                                )
2956                                .when_some(self.options.scroll_bounce, |bounce, on| {
2957                                    bounce.enabled(on)
2958                                })
2959                            })
2960                            .into_any_element(),
2961                        ),
2962                    )
2963                }
2964            });
2965
2966        div()
2967            .size_full()
2968            .children(loading_view)
2969            .when(!loading, |this| {
2970                this.child(inner_table)
2971                    .child(ScrollableMask::new(
2972                        Axis::Horizontal,
2973                        &self.horizontal_scroll_handle,
2974                    ))
2975                    // Keep vertical wheel scrolling from leaking into an
2976                    // ancestor scroller. Skipped when the table is empty:
2977                    // the `uniform_list` is not rendered then, so the
2978                    // handle's offset and `max_offset` are stale.
2979                    .when(rows_count > 0, |this| {
2980                        this.child(ScrollableMask::new(
2981                            Axis::Vertical,
2982                            &self.vertical_scroll_handle.0.borrow().base_handle,
2983                        ))
2984                    })
2985                    .when(has_right_click, |this| {
2986                        this.on_mouse_down_out(cx.listener(|this, e, window, cx| {
2987                            this.on_row_right_click(e, None, window, cx);
2988                            cx.notify();
2989                        }))
2990                    })
2991            })
2992            .on_prepaint({
2993                let state = cx.entity();
2994                move |bounds, _, cx| state.update(cx, |state, _| state.bounds = bounds)
2995            })
2996            .when(!window.is_inspector_picking(cx), |this| {
2997                this.child(
2998                    div()
2999                        .absolute()
3000                        .top_0()
3001                        .size_full()
3002                        .when(self.options.scrollbar_visible.bottom, |this| {
3003                            this.child(self.render_horizontal_scrollbar(window, cx))
3004                        })
3005                        .when(
3006                            self.options.scrollbar_visible.right && rows_count > 0,
3007                            |this| this.children(self.render_vertical_scrollbar(window, cx)),
3008                        ),
3009                )
3010            })
3011    }
3012}
3013
3014#[cfg(test)]
3015mod tests {
3016    use gpui::{AnyView, App, Entity, StyleRefinement, TestAppContext};
3017
3018    use super::*;
3019
3020    struct WidthsDelegate;
3021
3022    struct BounceDelegate;
3023
3024    impl TableDelegate for BounceDelegate {
3025        fn columns_count(&self, _: &App) -> usize {
3026            1
3027        }
3028        fn rows_count(&self, _: &App) -> usize {
3029            40
3030        }
3031        fn column(&self, _: usize, _: &App) -> Column {
3032            Column::new("value", "Value")
3033        }
3034        fn render_td(
3035            &mut self,
3036            row: usize,
3037            _: usize,
3038            _: &mut Window,
3039            _: &mut Context<TableState<Self>>,
3040        ) -> impl IntoElement {
3041            div().child(row.to_string())
3042        }
3043    }
3044
3045    struct BounceTable(Entity<TableState<BounceDelegate>>);
3046
3047    impl Render for BounceTable {
3048        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3049            div()
3050                .w(px(240.))
3051                .h(px(200.))
3052                .child(DataTable::new(&self.0).scroll_bounce(true))
3053        }
3054    }
3055
3056    #[gpui::test]
3057    fn scroll_bounce_table_keeps_headers_fixed_and_accepts_new_wheel_input(
3058        cx: &mut TestAppContext,
3059    ) {
3060        cx.update(crate::init);
3061        let (view, cx) = cx.add_window_view(|window, cx| {
3062            BounceTable(cx.new(|cx| TableState::new(BounceDelegate, window, cx)))
3063        });
3064        cx.update(|window, cx| window.draw(cx).clear(cx));
3065        let state = view.read_with(cx, |view, _| view.0.clone());
3066        let header = state.read_with(cx, |state, _| state.col_groups[0].bounds);
3067        let wheel = |cx: &mut gpui::VisualTestContext, dy| {
3068            cx.simulate_event(gpui::ScrollEvent {
3069                position: gpui::point(px(100.), px(100.)),
3070                delta: gpui::ScrollDelta::Lines(gpui::point(0., dy)),
3071                ..Default::default()
3072            });
3073        };
3074        for (dy, phase) in [
3075            (-10000., gpui::TouchPhase::Started),
3076            (0., gpui::TouchPhase::Ended),
3077        ] {
3078            cx.simulate_event(gpui::ScrollEvent {
3079                position: gpui::point(px(100.), px(100.)),
3080                delta: gpui::ScrollDelta::Pixels(gpui::point(px(0.), px(dy))),
3081                touch_phase: phase,
3082                ..Default::default()
3083            });
3084        }
3085        cx.update(|window, cx| window.draw(cx).clear(cx));
3086        let end = state.read_with(cx, |state, _| {
3087            state
3088                .vertical_scroll_handle
3089                .0
3090                .borrow()
3091                .base_handle
3092                .offset()
3093                .y
3094        });
3095        assert!(end < px(0.));
3096        cx.executor().advance_clock(Duration::from_millis(200));
3097        cx.update(|window, cx| window.draw(cx).clear(cx));
3098        assert_eq!(
3099            state.read_with(cx, |state, _| state.col_groups[0].bounds),
3100            header
3101        );
3102        wheel(cx, 2.);
3103        assert!(
3104            state.read_with(cx, |state, _| state
3105                .vertical_scroll_handle
3106                .0
3107                .borrow()
3108                .base_handle
3109                .offset()
3110                .y)
3111                > end
3112        );
3113    }
3114
3115    #[gpui::test]
3116    fn programmatic_selection_keeps_the_viewport_but_keyboard_reveals(cx: &mut TestAppContext) {
3117        cx.update(crate::init);
3118        let (view, cx) = cx.add_window_view(|window, cx| {
3119            BounceTable(cx.new(|cx| TableState::new(BounceDelegate, window, cx)))
3120        });
3121        cx.update(|window, cx| window.draw(cx).clear(cx));
3122        let state = view.read_with(cx, |view, _| view.0.clone());
3123        let offset = |cx: &mut gpui::VisualTestContext| {
3124            state.read_with(cx, |state, _| {
3125                state
3126                    .vertical_scroll_handle
3127                    .0
3128                    .borrow()
3129                    .base_handle
3130                    .offset()
3131                    .y
3132            })
3133        };
3134
3135        // Select row 0, then scroll far away from it.
3136        state.update(cx, |state, cx| state.set_selected_row(0, cx));
3137        state.update(cx, |state, cx| state.scroll_to_row(39, cx));
3138        cx.update(|window, cx| window.draw(cx).clear(cx));
3139        let scrolled = offset(cx);
3140        assert!(scrolled < px(0.));
3141
3142        // A refresh re-asserts the selection on another off-screen row.
3143        state.update(cx, |state, cx| state.set_selected_row(2, cx));
3144        cx.update(|window, cx| window.draw(cx).clear(cx));
3145        assert_eq!(offset(cx), scrolled);
3146        state.update(cx, |state, cx| state.set_selected_cell(1, 0, cx));
3147        cx.update(|window, cx| window.draw(cx).clear(cx));
3148        assert_eq!(offset(cx), scrolled);
3149        state.update(cx, |state, cx| {
3150            state.set_selection(TableSelection::Row(3), cx)
3151        });
3152        cx.update(|window, cx| window.draw(cx).clear(cx));
3153        assert_eq!(offset(cx), scrolled);
3154
3155        // Keyboard navigation still brings the selection into view.
3156        cx.update(|window, cx| {
3157            state.update(cx, |state, cx| {
3158                state.action_select_next(&SelectDown, window, cx)
3159            })
3160        });
3161        cx.update(|window, cx| window.draw(cx).clear(cx));
3162        assert_eq!(
3163            state.read_with(cx, |state, _| state.selected_row()),
3164            Some(4)
3165        );
3166        assert!(offset(cx) > scrolled);
3167    }
3168
3169    struct ThreeRowsDelegate;
3170
3171    impl TableDelegate for ThreeRowsDelegate {
3172        fn columns_count(&self, _: &App) -> usize {
3173            1
3174        }
3175        fn rows_count(&self, _: &App) -> usize {
3176            3
3177        }
3178        fn column(&self, _: usize, _: &App) -> Column {
3179            Column::new("value", "Value")
3180        }
3181        fn render_td(
3182            &mut self,
3183            row: usize,
3184            _: usize,
3185            _: &mut Window,
3186            _: &mut Context<TableState<Self>>,
3187        ) -> impl IntoElement {
3188            div().child(row.to_string())
3189        }
3190    }
3191
3192    /// Holds the table, and counts how often it is drawn.
3193    struct StripedPanel {
3194        table: Entity<TableState<ThreeRowsDelegate>>,
3195        renders: usize,
3196    }
3197
3198    impl Render for StripedPanel {
3199        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3200            self.renders += 1;
3201            div()
3202                .size_full()
3203                .child(DataTable::new(&self.table).stripe(true))
3204        }
3205    }
3206
3207    /// Draws the panel as a cached view, the way `TabPanel` draws a dock panel.
3208    struct CachedPanel(Entity<StripedPanel>);
3209
3210    impl Render for CachedPanel {
3211        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3212            div()
3213                .w(px(240.))
3214                .h(px(400.))
3215                .child(AnyView::from(self.0.clone()).cached(StyleRefinement::default().size_full()))
3216        }
3217    }
3218
3219    /// The filler rows a striped table adds below its last row must not make
3220    /// it scroll, and so notify, every time it is drawn. That kept a cached
3221    /// view holding the table from ever being reused.
3222    #[gpui::test]
3223    fn striped_table_with_few_rows_lets_a_cached_view_be_reused(cx: &mut TestAppContext) {
3224        cx.update(crate::init);
3225        let (view, cx) = cx.add_window_view(|window, cx| {
3226            let table = cx.new(|cx| TableState::new(ThreeRowsDelegate, window, cx));
3227            CachedPanel(cx.new(|_| StripedPanel { table, renders: 0 }))
3228        });
3229        let panel = view.read_with(cx, |view, _| view.0.clone());
3230        let table = panel.read_with(cx, |panel, _| panel.table.clone());
3231        let draw = |cx: &mut gpui::VisualTestContext| {
3232            cx.update(|window, cx| window.draw(cx).clear(cx));
3233        };
3234        draw(cx);
3235        // Drawn again now that it knows its height, with the filler rows.
3236        table.update(cx, |_, cx| cx.notify());
3237        draw(cx);
3238        let renders = panel.read_with(cx, |panel, _| panel.renders);
3239        draw(cx);
3240        draw(cx);
3241        assert_eq!(panel.read_with(cx, |panel, _| panel.renders), renders);
3242    }
3243
3244    impl TableDelegate for WidthsDelegate {
3245        fn columns_count(&self, _: &App) -> usize {
3246            6
3247        }
3248
3249        fn rows_count(&self, _: &App) -> usize {
3250            0
3251        }
3252
3253        fn column(&self, col_ix: usize, _: &App) -> Column {
3254            match col_ix {
3255                0 => Column::new("narrow", "Narrow")
3256                    .min_width(px(80.))
3257                    .width(px(40.)),
3258                1 => Column::new("wide", "Wide")
3259                    .max_width(px(120.))
3260                    .width(px(300.)),
3261                // `width` alone below the default `min_width` of 20px.
3262                2 => Column::new("tiny", "Tiny").width(px(10.)),
3263                // The default resize protection does not limit initial width.
3264                3 => Column::new("wide_default", "Wide Default").width(px(2000.)),
3265                // Applications can explicitly allow wider resize ranges.
3266                4 => Column::new("wide_explicit", "Wide Explicit")
3267                    .max_width(px(2400.))
3268                    .width(px(2000.)),
3269                // `min_width` above `max_width` must not panic.
3270                _ => Column::new("inverted", "Inverted")
3271                    .min_width(px(200.))
3272                    .max_width(px(100.)),
3273            }
3274        }
3275
3276        fn render_td(
3277            &mut self,
3278            _: usize,
3279            _: usize,
3280            _: &mut Window,
3281            _: &mut Context<TableState<Self>>,
3282        ) -> impl IntoElement {
3283            div()
3284        }
3285    }
3286
3287    #[gpui::test]
3288    fn column_resize_bounds_preserve_initial_widths(cx: &mut TestAppContext) {
3289        cx.skip_drawing();
3290        let window = cx.add_window(|window, cx| TableState::new(WidthsDelegate, window, cx));
3291
3292        window
3293            .update(cx, |table, window, cx| {
3294                let widths = |table: &TableState<WidthsDelegate>| {
3295                    table
3296                        .col_groups
3297                        .iter()
3298                        .map(|col_group| col_group.width)
3299                        .collect::<Vec<_>>()
3300                };
3301                assert_eq!(
3302                    widths(table),
3303                    [px(40.), px(300.), px(10.), px(2000.), px(2000.), px(100.)]
3304                );
3305
3306                for ix in 0..table.col_groups.len() {
3307                    table.resize_cols(ix, px(10000.), window, cx);
3308                }
3309                assert_eq!(
3310                    widths(table),
3311                    [
3312                        px(1200.),
3313                        px(120.),
3314                        px(1200.),
3315                        px(1200.),
3316                        px(2400.),
3317                        px(100.)
3318                    ]
3319                );
3320
3321                for ix in 0..table.col_groups.len() {
3322                    table.resize_cols(ix, px(-100.), window, cx);
3323                }
3324                assert_eq!(
3325                    widths(table),
3326                    [px(80.), px(20.), px(20.), px(20.), px(20.), px(100.)]
3327                );
3328            })
3329            .unwrap();
3330    }
3331}