Skip to main content

gpui_component/table/
data_table.rs

1use crate::{
2    ActiveTheme, Sizable, Size, ThemeStyled as _,
3    actions::{
4        Cancel, SelectDown, SelectFirst, SelectLast, SelectNextColumn, SelectPageDown,
5        SelectPageUp, SelectPrevColumn, SelectUp,
6    },
7    scroll::ScrollbarMode,
8    table::{TableDelegate, TableState},
9};
10use gpui::{
11    App, Edges, Entity, Focusable, InteractiveElement, IntoElement, KeyBinding, ParentElement,
12    Pixels, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window, div,
13    prelude::FluentBuilder,
14};
15use gpui_base::TestSupportExt as _;
16
17const CONTEXT: &'static str = "DataTable";
18pub(super) fn init(cx: &mut App) {
19    cx.bind_keys([
20        KeyBinding::new("escape", Cancel, Some(CONTEXT)),
21        KeyBinding::new("up", SelectUp, Some(CONTEXT)),
22        KeyBinding::new("down", SelectDown, Some(CONTEXT)),
23        KeyBinding::new("left", SelectPrevColumn, Some(CONTEXT)),
24        KeyBinding::new("right", SelectNextColumn, Some(CONTEXT)),
25        KeyBinding::new("home", SelectFirst, Some(CONTEXT)),
26        KeyBinding::new("end", SelectLast, Some(CONTEXT)),
27        KeyBinding::new("pageup", SelectPageUp, Some(CONTEXT)),
28        KeyBinding::new("pagedown", SelectPageDown, Some(CONTEXT)),
29    ]);
30}
31
32pub(super) struct TableOptions {
33    pub(super) scroll_bounce: Option<bool>,
34    pub(super) scrollbar_visible: Edges<bool>,
35    pub(super) scrollbar_mode: Option<ScrollbarMode>,
36    /// Set stripe style of the table.
37    pub(super) stripe: bool,
38    /// Set to use border style of the table.
39    pub(super) bordered: bool,
40    /// Draw the border on the inner edge of the fixed columns.
41    pub(super) fixed_cols_border: bool,
42    /// The cell size of the table.
43    pub(super) size: Size,
44    /// Height of each header row. `None` uses [`Size::table_row_height`].
45    pub(super) header_row_height: Option<Pixels>,
46}
47
48impl Default for TableOptions {
49    fn default() -> Self {
50        Self {
51            scroll_bounce: None,
52            scrollbar_visible: Edges::all(true),
53            scrollbar_mode: None,
54            stripe: false,
55            bordered: true,
56            fixed_cols_border: true,
57            size: Size::default(),
58            header_row_height: None,
59        }
60    }
61}
62
63/// A table element with support for row, column, and cell selection.
64///
65/// # Features
66///
67/// - **Multiple Selection Modes**: Support for row, column, and cell selection
68/// - **Cell Selection**: Click to select individual cells, with keyboard navigation
69/// - **Virtual Scrolling**: Efficient rendering of large datasets
70/// - **Resizable Columns**: Drag column borders to resize
71/// - **Movable Columns**: Drag column headers to reorder
72/// - **Fixed Columns**: Pin columns to the left or right side
73/// - **Sortable Columns**: Click column headers to sort
74/// - **Context Menus**: Right-click support for rows and cells
75///
76/// # Cell Selection Mode
77///
78/// When cell selection is enabled via [`TableState::cell_selectable()`]:
79/// - Click on cells to select them
80/// - A row header column appears on the left for selecting entire rows
81///   (use [`TableState::row_header()`] to hide it)
82/// - Keyboard navigation (arrow keys, Tab, Home, End, PageUp, PageDown) works at cell level
83/// - Right-click and double-click events are supported
84///
85/// See [`TableState`] for more details on cell selection.
86///
87/// # Example
88///
89/// ```rust,ignore
90/// let table_state = cx.new(|cx| {
91///     TableState::new(delegate, cx)
92///         .cell_selectable(true)
93///         .row_selectable(true)
94/// });
95///
96/// DataTable::new(&table_state)
97///     .stripe(true)
98///     .bordered(true)
99/// ```
100#[derive(IntoElement)]
101pub struct DataTable<D: TableDelegate> {
102    state: Entity<TableState<D>>,
103    options: TableOptions,
104    focus_ring_enabled: bool,
105    accessibility_label: Option<SharedString>,
106}
107
108impl<D> DataTable<D>
109where
110    D: TableDelegate,
111{
112    /// Create a new DataTable element with the given [`TableState`].
113    pub fn new(state: &Entity<TableState<D>>) -> Self {
114        Self {
115            state: state.clone(),
116            options: TableOptions::default(),
117            focus_ring_enabled: true,
118            accessibility_label: None,
119        }
120    }
121
122    /// Sets the label exposed to accessibility clients, the table's name.
123    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
124        self.accessibility_label = Some(label.into());
125        self
126    }
127
128    /// Set to use stripe style of the table, default to false.
129    pub fn stripe(mut self, stripe: bool) -> Self {
130        self.options.stripe = stripe;
131        self
132    }
133
134    /// Bounce the rows at the vertical boundaries, keeping headers and
135    /// scrollbars fixed. On by default on iOS,
136    /// Android and macOS, off elsewhere.
137    pub fn scroll_bounce(mut self, enabled: bool) -> Self {
138        self.options.scroll_bounce = Some(enabled);
139        self
140    }
141
142    /// Set to use border style of the table, default to true.
143    pub fn bordered(mut self, bordered: bool) -> Self {
144        self.options.bordered = bordered;
145        self
146    }
147
148    /// Set the height of each header row.
149    ///
150    /// Column-group rows use the same height, so the whole header is this
151    /// height times the number of header rows. Body rows keep the height from
152    /// [`Size::table_row_height`]. When this is unset, header rows use that
153    /// same height.
154    pub fn header_row_height(mut self, height: impl Into<Pixels>) -> Self {
155        self.options.header_row_height = Some(height.into());
156        self
157    }
158
159    /// Set whether to draw the border on the inner edge of the fixed columns,
160    /// the right edge of left-fixed columns and the left edge of right-fixed
161    /// columns, default to true.
162    ///
163    /// Turn it off when the fixed cells draw that edge themselves, so the
164    /// boundary is not drawn twice.
165    pub fn fixed_cols_border(mut self, fixed_cols_border: bool) -> Self {
166        self.options.fixed_cols_border = fixed_cols_border;
167        self
168    }
169
170    /// Set scrollbar visibility.
171    pub fn scrollbar_visible(mut self, vertical: bool, horizontal: bool) -> Self {
172        self.options.scrollbar_visible = Edges {
173            right: vertical,
174            bottom: horizontal,
175            ..Default::default()
176        };
177        self
178    }
179
180    /// Set the show mode of both the vertical and horizontal scrollbars.
181    ///
182    /// Defaults to the theme's [`ScrollbarMode`]. A data grid can use
183    /// [`ScrollbarMode::Always`] so that the columns out of view are visible
184    /// without scrolling.
185    pub fn scrollbar_mode(mut self, mode: ScrollbarMode) -> Self {
186        self.options.scrollbar_mode = Some(mode);
187        self
188    }
189}
190
191impl<D> Sizable for DataTable<D>
192where
193    D: TableDelegate,
194{
195    fn with_size(mut self, size: impl Into<Size>) -> Self {
196        self.options.size = size.into();
197        self
198    }
199}
200
201impl<D> crate::FocusableExt for DataTable<D>
202where
203    D: TableDelegate,
204{
205    fn focus_ring(mut self, enabled: bool) -> Self {
206        self.focus_ring_enabled = enabled;
207        self
208    }
209
210    fn is_focus_ring_enabled(&self) -> bool {
211        self.focus_ring_enabled
212    }
213}
214
215impl<D> RenderOnce for DataTable<D>
216where
217    D: TableDelegate,
218{
219    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
220        let bordered = self.options.bordered;
221        let focus_ring_enabled = self.focus_ring_enabled;
222        let focus_handle = self.state.focus_handle(cx);
223        let (role, rows_count, columns_count) = self.state.update(cx, |state, cx| {
224            state.options = self.options;
225            // A table that selects rows or cells is a grid.
226            let role = if state.row_selectable || state.cell_selectable {
227                gpui::Role::Grid
228            } else {
229                gpui::Role::Table
230            };
231            let delegate = state.delegate();
232            (role, delegate.rows_count(cx), delegate.columns_count(cx))
233        });
234
235        // The element that holds the keyboard focus is the table's
236        // accessibility node: GPUI reports focus only on an element with a
237        // role, and otherwise falls back to the window.
238        div()
239            .id("table")
240            .test_support()
241            .role(role)
242            .when_some(self.accessibility_label, |this, label| {
243                this.aria_label(label)
244            })
245            // The counts cover every row, not just the rendered ones, plus
246            // the header row.
247            .aria_row_count(rows_count + 1)
248            .aria_column_count(columns_count)
249            .size_full()
250            .key_context(CONTEXT)
251            .track_focus(&focus_handle)
252            .on_action(window.listener_for(&self.state, TableState::action_cancel))
253            .on_action(window.listener_for(&self.state, TableState::action_select_next))
254            .on_action(window.listener_for(&self.state, TableState::action_select_prev))
255            .on_action(window.listener_for(&self.state, TableState::action_select_next_col))
256            .on_action(window.listener_for(&self.state, TableState::action_select_prev_col))
257            .on_action(window.listener_for(&self.state, TableState::action_select_first_column))
258            .on_action(window.listener_for(&self.state, TableState::action_select_last_column))
259            .on_action(window.listener_for(&self.state, TableState::action_select_page_up))
260            .on_action(window.listener_for(&self.state, TableState::action_select_page_down))
261            .bg(cx.theme().tokens.table)
262            .when(bordered, |this| {
263                this.rounded(cx.theme().radius)
264                    .border_1()
265                    .border_color(cx.theme().border)
266            })
267            .child(self.state)
268            // Clicking a row focuses the table too, so only keyboard focus
269            // shows it, as CSS `:focus-visible` does.
270            .when(
271                focus_ring_enabled
272                    && focus_handle.is_focused(window)
273                    && window.last_input_was_keyboard(),
274                |this| this.focus_ring_style(window, cx),
275            )
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use gpui::{
282        AppContext as _, Context, Entity, Render, TestAppContext, VisualTestContext, Window, div,
283        px,
284    };
285
286    use super::*;
287    use crate::{
288        FocusableExt as _,
289        table::{Column, TableState},
290    };
291
292    struct RowsDelegate;
293
294    impl TableDelegate for RowsDelegate {
295        fn columns_count(&self, _: &App) -> usize {
296            1
297        }
298        fn rows_count(&self, _: &App) -> usize {
299            3
300        }
301        fn column(&self, _: usize, _: &App) -> Column {
302            Column::new("name", "Name")
303        }
304        fn render_td(
305            &mut self,
306            row: usize,
307            _: usize,
308            _: &mut Window,
309            _: &mut Context<TableState<Self>>,
310        ) -> impl IntoElement {
311            div().child(row.to_string())
312        }
313    }
314
315    struct FocusRingHarness {
316        state: Entity<TableState<RowsDelegate>>,
317        focus_ring: bool,
318    }
319
320    impl Render for FocusRingHarness {
321        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
322            div()
323                .w(px(240.))
324                .h(px(160.))
325                .child(DataTable::new(&self.state).focus_ring(self.focus_ring))
326        }
327    }
328
329    /// Focuses the table and moves the selection with the keyboard, the way
330    /// a user arriving with up/down sees the ring.
331    fn keyboard_focused_table(cx: &mut TestAppContext, focus_ring: bool) -> &mut VisualTestContext {
332        cx.update(crate::init);
333        let (view, cx) = cx.add_window_view(move |window, cx| FocusRingHarness {
334            state: cx.new(|cx| TableState::new(RowsDelegate, window, cx)),
335            focus_ring,
336        });
337        let state = view.read_with(cx, |view, _| view.state.clone());
338        cx.update(|window, cx| {
339            let handle = state.focus_handle(cx);
340            window.focus(&handle, cx);
341        });
342        cx.simulate_keystrokes("down");
343        cx.update(|window, cx| window.draw(cx).clear(cx));
344        cx
345    }
346
347    #[gpui::test]
348    fn test_data_table_builder(cx: &mut TestAppContext) {
349        cx.update(crate::init);
350        let (view, cx) = cx.add_window_view(|window, cx| FocusRingHarness {
351            state: cx.new(|cx| TableState::new(RowsDelegate, window, cx)),
352            focus_ring: true,
353        });
354        let state = view.read_with(cx, |view, _| view.state.clone());
355        assert!(DataTable::new(&state).is_focus_ring_enabled());
356
357        let table = DataTable::new(&state)
358            .stripe(true)
359            .bordered(false)
360            .scroll_bounce(false)
361            .header_row_height(px(32.))
362            .fixed_cols_border(false)
363            .scrollbar_visible(false, true)
364            .scrollbar_mode(ScrollbarMode::Always)
365            .with_size(Size::Small)
366            .focus_ring(false);
367        assert!(table.options.stripe);
368        assert!(!table.options.bordered);
369        assert_eq!(table.options.scroll_bounce, Some(false));
370        assert_eq!(table.options.header_row_height, Some(px(32.)));
371        assert!(!table.options.fixed_cols_border);
372        assert!(!table.options.scrollbar_visible.right);
373        assert!(table.options.scrollbar_visible.bottom);
374        assert_eq!(table.options.scrollbar_mode, Some(ScrollbarMode::Always));
375        assert_eq!(table.options.size, Size::Small);
376        assert!(!table.is_focus_ring_enabled());
377        assert!(table.focus_ring(true).is_focus_ring_enabled());
378    }
379
380    #[gpui::test]
381    fn data_table_draws_the_focus_ring_by_default(cx: &mut TestAppContext) {
382        let cx = keyboard_focused_table(cx, true);
383        assert!(
384            cx.debug_bounds("focus-ring").is_some(),
385            "a keyboard-focused table draws its focus ring"
386        );
387    }
388
389    #[gpui::test]
390    fn data_table_focus_ring_can_be_turned_off(cx: &mut TestAppContext) {
391        let cx = keyboard_focused_table(cx, false);
392        assert!(
393            cx.debug_bounds("focus-ring").is_none(),
394            "`focus_ring(false)` must not draw a ring"
395        );
396    }
397}