Skip to main content

gpui_deck/
table.rs

1//! Shared column geometry and native semantics for ordinary data tables.
2
3use gpui::{
4    AnyElement, App, Div, ElementId, InteractiveElement as _, IntoElement, ParentElement, Pixels,
5    RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled,
6    Window, accesskit::SortDirection, div, prelude::FluentBuilder as _, px,
7};
8
9use crate::{StyledExt as _, TestSupportExt as _, a11y_disabled::A11yDisabledExt as _};
10
11/// One column track, shared by every row in a [`Table`].
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct TableColumn {
14    width: ColumnWidth,
15}
16
17#[derive(Clone, Copy, Debug, PartialEq)]
18enum ColumnWidth {
19    Fixed(Pixels),
20    Flex(f32),
21}
22
23impl TableColumn {
24    /// A fixed-width column that does not shrink when its table overflows.
25    pub fn fixed(width: Pixels) -> Self {
26        assert!(f32::from(width).is_finite() && width >= px(0.));
27        Self {
28            width: ColumnWidth::Fixed(width),
29        }
30    }
31
32    /// A column receiving this positive share of the space after fixed columns.
33    pub fn flex(weight: f32) -> Self {
34        assert!(weight.is_finite() && weight > 0.);
35        Self {
36            width: ColumnWidth::Flex(weight),
37        }
38    }
39}
40
41/// An unstyled table with one shared column definition.
42///
43/// Header, body, and footer render as native row groups. Header cells have the
44/// ColumnHeader role; ordinary cells have Cell or an explicitly chosen RowHeader
45/// role. Indices are zero-based, matching AccessKit, and include header/footer
46/// rows. Tables and their structural parts introduce no keyboard focus stops.
47/// Interactive children retain their own normal focus and activation behavior.
48///
49/// Every row must contain exactly one cell per column. Column widths belong to
50/// this table, while cell padding and content styles belong to the application.
51/// Rows reserve their horizontal layout for these tracks: apply spacing inside
52/// cells, not with row padding, margins, or gaps. Give the table an explicit
53/// minimum width and compose it with ScrollArea when columns must overflow a
54/// narrower viewport. This component does not virtualize rows or manage data
55/// sorting, filtering, selection, or spans.
56#[derive(IntoElement)]
57pub struct Table {
58    id: ElementId,
59    base: crate::ObservedElement<gpui::Stateful<Div>>,
60    columns: Vec<TableColumn>,
61    header: Option<TableRow>,
62    rows: Vec<TableRow>,
63    footer: Option<TableRow>,
64    caption: Option<TableCaption>,
65    label: Option<SharedString>,
66}
67
68impl Table {
69    pub fn new(id: impl Into<ElementId>, columns: impl IntoIterator<Item = TableColumn>) -> Self {
70        let columns: Vec<_> = columns.into_iter().collect();
71        assert!(!columns.is_empty(), "a table needs at least one column");
72        let id = id.into();
73        Self {
74            base: div().id(id.clone()).test_support(),
75            id,
76            columns,
77            header: None,
78            rows: Vec::new(),
79            footer: None,
80            caption: None,
81            label: None,
82        }
83    }
84
85    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
86        self.label = Some(label.into());
87        self
88    }
89
90    /// Sets the single column-header row.
91    pub fn header(mut self, row: TableRow) -> Self {
92        self.header = Some(row);
93        self
94    }
95
96    pub fn row(mut self, row: TableRow) -> Self {
97        self.rows.push(row);
98        self
99    }
100
101    pub fn rows(mut self, rows: impl IntoIterator<Item = TableRow>) -> Self {
102        self.rows.extend(rows);
103        self
104    }
105
106    /// Sets a single footer row, such as a total or summary.
107    pub fn footer(mut self, row: TableRow) -> Self {
108        self.footer = Some(row);
109        self
110    }
111
112    /// Adds a caption after the table's row groups.
113    ///
114    /// Supply [`Self::accessibility_label`] separately; a visible caption does
115    /// not automatically become the table's native accessible name.
116    pub fn caption(mut self, caption: TableCaption) -> Self {
117        self.caption = Some(caption);
118        self
119    }
120}
121
122impl Styled for Table {
123    fn style(&mut self) -> &mut StyleRefinement {
124        self.base.style()
125    }
126}
127
128impl RenderOnce for Table {
129    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
130        let row_count = self.rows.len()
131            + usize::from(self.header.is_some())
132            + usize::from(self.footer.is_some());
133        let body_start = usize::from(self.header.is_some());
134        let footer_index = body_start + self.rows.len();
135        self.base
136            .role(Role::Table)
137            .aria_row_count(row_count)
138            .aria_column_count(self.columns.len())
139            .when_some(self.label, |base, label| base.aria_label(label))
140            .flex()
141            .flex_col()
142            .when_some(self.header, |base, row| {
143                base.child(
144                    div()
145                        .id((self.id.clone(), "header"))
146                        .test_support()
147                        .role(Role::RowGroup)
148                        .w_full()
149                        .flex_shrink_0()
150                        .child(row.render_row(&self.columns, 0, true)),
151                )
152            })
153            .child(
154                div()
155                    .id((self.id.clone(), "body"))
156                    .test_support()
157                    .role(Role::RowGroup)
158                    .w_full()
159                    .flex()
160                    .flex_col()
161                    .flex_shrink_0()
162                    .children(self.rows.into_iter().enumerate().map(|(index, row)| {
163                        row.render_row(&self.columns, body_start + index, false)
164                    })),
165            )
166            .when_some(self.footer, |base, row| {
167                base.child(
168                    div()
169                        .id((self.id.clone(), "footer"))
170                        .test_support()
171                        .role(Role::RowGroup)
172                        .w_full()
173                        .flex_shrink_0()
174                        .child(row.render_row(&self.columns, footer_index, false)),
175                )
176            })
177            .when_some(self.caption, |base, caption| base.child(caption))
178    }
179}
180
181/// A table-owned row. Build its cells with [`Self::cell`] or [`Self::cells`].
182///
183/// The owning Table supplies the shared column tracks and native row index.
184/// Style backgrounds, borders, and height here; horizontal spacing belongs to
185/// cells so every row retains the same column geometry.
186pub struct TableRow {
187    base: crate::ObservedElement<gpui::Stateful<Div>>,
188    cells: Vec<TableCell>,
189}
190
191impl TableRow {
192    pub fn new(id: impl Into<ElementId>) -> Self {
193        Self {
194            base: div().id(id).test_support(),
195            cells: Vec::new(),
196        }
197    }
198
199    pub fn cell(mut self, cell: TableCell) -> Self {
200        self.cells.push(cell);
201        self
202    }
203
204    pub fn cells(mut self, cells: impl IntoIterator<Item = TableCell>) -> Self {
205        self.cells.extend(cells);
206        self
207    }
208
209    /// Exposes application-owned row selection without adding a focus stop.
210    pub fn selected(mut self, selected: bool) -> Self {
211        self.base = self.base.aria_selected(selected);
212        self
213    }
214
215    fn render_row(
216        self,
217        columns: &[TableColumn],
218        row: usize,
219        header: bool,
220    ) -> impl IntoElement + use<> {
221        assert_eq!(
222            self.cells.len(),
223            columns.len(),
224            "every table row needs one cell per column"
225        );
226        self.base
227            .role(Role::Row)
228            .aria_row_index(row)
229            .flex()
230            .flex_row()
231            .flex_nowrap()
232            .flex_shrink_0()
233            .w_full()
234            .min_w_0()
235            .px_0()
236            .mx_0()
237            .gap_0()
238            .children(
239                self.cells
240                    .into_iter()
241                    .zip(columns.iter().copied())
242                    .enumerate()
243                    .map(|(column, (cell, track))| cell.render_cell(track, row, column, header)),
244            )
245    }
246}
247
248impl Styled for TableRow {
249    fn style(&mut self) -> &mut StyleRefinement {
250        self.base.style()
251    }
252}
253
254/// A cell whose contents and presentation belong to the application.
255///
256/// Styles apply to the content surface inside a structural column track, so
257/// different header/body padding cannot change column alignment. The outer
258/// track owns the supplied ID, cell role, and row/column indices.
259pub struct TableCell {
260    base: crate::ObservedElement<gpui::Stateful<Div>>,
261    style: StyleRefinement,
262    children: Vec<AnyElement>,
263    row_header: bool,
264    label: Option<SharedString>,
265    sort_direction: Option<SortDirection>,
266}
267
268impl TableCell {
269    pub fn new(id: impl Into<ElementId>) -> Self {
270        Self {
271            base: div().id(id).test_support(),
272            style: StyleRefinement::default(),
273            children: Vec::new(),
274            row_header: false,
275            label: None,
276            sort_direction: None,
277        }
278    }
279
280    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
281        self.label = Some(label.into());
282        self
283    }
284
285    /// Marks a body or footer cell as a row header. Column-header rows take precedence.
286    pub fn row_header(mut self, row_header: bool) -> Self {
287        self.row_header = row_header;
288        self
289    }
290
291    /// Exposes the active sort direction on a column-header cell.
292    ///
293    /// `None` omits the property. Body and footer cells ignore this value.
294    pub fn sort_direction(mut self, direction: Option<SortDirection>) -> Self {
295        self.sort_direction = direction;
296        self
297    }
298
299    fn render_cell(
300        self,
301        track: TableColumn,
302        row: usize,
303        column: usize,
304        header: bool,
305    ) -> impl IntoElement {
306        let role = if header {
307            Role::ColumnHeader
308        } else if self.row_header {
309            Role::RowHeader
310        } else {
311            Role::Cell
312        };
313        let base = self
314            .base
315            .role(role)
316            .aria_row_index(row)
317            .aria_column_index(column)
318            .when_some(self.label, |base, label| base.aria_label(label))
319            .flex()
320            .flex_col()
321            .min_w_0()
322            .flex_shrink_0();
323        let base = match track.width {
324            ColumnWidth::Fixed(width) => base.w(width),
325            ColumnWidth::Flex(weight) => base.flex_basis(px(0.)).flex_grow(weight),
326        };
327        base.child(
328            div()
329                .min_w_0()
330                .w_full()
331                .flex_1()
332                .refine_style(&self.style)
333                .children(self.children),
334        )
335        .a11y_sort(self.sort_direction.filter(|_| header))
336    }
337}
338
339impl Styled for TableCell {
340    fn style(&mut self) -> &mut StyleRefinement {
341        &mut self.style
342    }
343}
344
345impl ParentElement for TableCell {
346    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
347        self.children.extend(elements);
348    }
349}
350
351/// A noninteractive caption rendered after a Table's rows.
352#[derive(IntoElement)]
353pub struct TableCaption {
354    base: crate::ObservedElement<gpui::Stateful<Div>>,
355}
356
357impl TableCaption {
358    pub fn new(id: impl Into<ElementId>) -> Self {
359        Self {
360            base: div().id(id).test_support(),
361        }
362    }
363}
364
365impl Styled for TableCaption {
366    fn style(&mut self) -> &mut StyleRefinement {
367        self.base.style()
368    }
369}
370
371impl ParentElement for TableCaption {
372    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
373        self.base.extend(elements);
374    }
375}
376
377impl RenderOnce for TableCaption {
378    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
379        self.base.role(Role::Caption).flex_shrink_0()
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use gpui::{Element as _, TestAppContext, accesskit};
386
387    use super::*;
388
389    #[gpui::test]
390    fn table_parts_expose_native_structure_without_focus_actions(cx: &mut TestAppContext) {
391        let window = cx.add_empty_window();
392        window.update(|window, cx| {
393            let row = || TableRow::new("row").cell(TableCell::new("cell").child("Value"));
394            let table = Table::new("table", [TableColumn::flex(1.)])
395                .accessibility_label("Sessions")
396                .header(row())
397                .row(row())
398                .footer(row())
399                .render(window, cx)
400                .into_element();
401            assert_eq!(table.a11y_role(), Some(Role::Table));
402            let mut node = accesskit::Node::new(Role::Table);
403            table.write_a11y_info(&mut node);
404            assert_eq!(node.label(), Some("Sessions"));
405            assert_eq!(node.row_count(), Some(3));
406            assert_eq!(node.column_count(), Some(1));
407            assert!(!node.supports_action(accesskit::Action::Focus));
408
409            let row = row()
410                .render_row(&[TableColumn::fixed(px(120.))], 2, false)
411                .into_element();
412            assert_eq!(row.a11y_role(), Some(Role::Row));
413            let mut node = accesskit::Node::new(Role::Row);
414            row.write_a11y_info(&mut node);
415            assert_eq!(node.row_index(), Some(2));
416            assert!(!node.supports_action(accesskit::Action::Focus));
417
418            for (header, row_header, role) in [
419                (true, false, Role::ColumnHeader),
420                (false, true, Role::RowHeader),
421                (false, false, Role::Cell),
422            ] {
423                let cell = TableCell::new("cell")
424                    .row_header(row_header)
425                    .accessibility_label("A session")
426                    .render_cell(TableColumn::flex(1.), 2, 1, header)
427                    .into_element();
428                assert_eq!(cell.a11y_role(), Some(role));
429                let mut node = accesskit::Node::new(role);
430                cell.write_a11y_info(&mut node);
431                assert_eq!(node.row_index(), Some(2));
432                assert_eq!(node.column_index(), Some(1));
433                assert_eq!(node.label(), Some("A session"));
434                assert!(!node.supports_action(accesskit::Action::Focus));
435                assert!(!node.supports_action(accesskit::Action::Click));
436            }
437            let caption = TableCaption::new("caption")
438                .child("Scheduled sessions")
439                .render(window, cx)
440                .into_element();
441            assert_eq!(caption.a11y_role(), Some(Role::Caption));
442        });
443    }
444
445    #[gpui::test]
446    fn selection_and_sort_direction_use_existing_native_nodes(cx: &mut TestAppContext) {
447        let window = cx.add_empty_window();
448        window.update(|_, _| {
449            for selected in [false, true] {
450                let row = TableRow::new("row")
451                    .selected(selected)
452                    .cell(TableCell::new("value"))
453                    .render_row(&[TableColumn::flex(1.)], 1, false)
454                    .into_element();
455                let mut node = accesskit::Node::new(Role::Row);
456                row.write_a11y_info(&mut node);
457                assert_eq!(node.is_selected(), Some(selected));
458                assert!(!node.supports_action(accesskit::Action::Focus));
459            }
460            for direction in [
461                None,
462                Some(SortDirection::Ascending),
463                Some(SortDirection::Descending),
464            ] {
465                for header in [false, true] {
466                    let cell = TableCell::new("heading")
467                        .sort_direction(direction)
468                        .render_cell(TableColumn::flex(1.), 0, 0, header)
469                        .into_element();
470                    let role = if header {
471                        Role::ColumnHeader
472                    } else {
473                        Role::Cell
474                    };
475                    let mut node = accesskit::Node::new(role);
476                    cell.write_a11y_info(&mut node);
477                    assert_eq!(cell.a11y_role(), Some(role));
478                    assert_eq!(node.sort_direction(), direction.filter(|_| header));
479                    assert!(!node.supports_action(accesskit::Action::Click));
480                }
481            }
482        });
483    }
484
485    #[cfg(feature = "test-support")]
486    #[gpui::test]
487    fn shared_tracks_align_cells_and_keep_child_button_traversal(cx: &mut TestAppContext) {
488        use gpui::{AppContext as _, Context, FocusHandle, Modifiers, Render, VisualTestContext};
489        use std::{cell::Cell, rc::Rc};
490
491        use crate::{Button, Root, test_support};
492
493        struct Sample {
494            before: FocusHandle,
495            action: FocusHandle,
496            after: FocusHandle,
497            clicks: Rc<Cell<usize>>,
498        }
499
500        impl Render for Sample {
501            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
502                let clicks = self.clicks.clone();
503                div()
504                    .flex()
505                    .flex_col()
506                    .child(
507                        Button::new("before")
508                            .track_focus(&self.before)
509                            .child("Before"),
510                    )
511                    .child(
512                        Table::new(
513                            "sample-table",
514                            [
515                                TableColumn::fixed(px(90.)),
516                                TableColumn::flex(1.),
517                                TableColumn::flex(2.),
518                            ],
519                        )
520                        .w(px(450.))
521                        .header(
522                            TableRow::new("header").cells([
523                                TableCell::new("head-0")
524                                    .sort_direction(Some(SortDirection::Ascending))
525                                    .p_3()
526                                    .child("Code"),
527                                TableCell::new("head-1").p_3().child("Name"),
528                                TableCell::new("head-2").p_3().child("Action"),
529                            ]),
530                        )
531                        .row(
532                            TableRow::new("body-row").selected(true).cells([
533                                TableCell::new("body-0").p_1().child("AB12"),
534                                TableCell::new("body-1").p_1().child("A long session name"),
535                                TableCell::new("body-2").p_1().child(
536                                    Button::new("table-action")
537                                        .track_focus(&self.action)
538                                        .on_click(move |_, _, _| clicks.set(clicks.get() + 1))
539                                        .child("Open"),
540                                ),
541                            ]),
542                        ),
543                    )
544                    .child(Button::new("after").track_focus(&self.after).child("After"))
545            }
546        }
547
548        fn draw(cx: &mut VisualTestContext) {
549            cx.update(|window, cx| window.draw(cx).clear(cx));
550        }
551
552        cx.update(crate::init);
553        let (root, cx) = cx.add_window_view(|window, cx| {
554            let view = cx.new(|cx| Sample {
555                before: cx.focus_handle(),
556                action: cx.focus_handle(),
557                after: cx.focus_handle(),
558                clicks: Rc::new(Cell::new(0)),
559            });
560            Root::new(view, window, cx)
561        });
562        let view = root
563            .read_with(cx, |root, _| root.view().clone())
564            .downcast::<Sample>()
565            .unwrap();
566        cx.update(|window, cx| {
567            window.activate_window();
568            let before = view.read(cx).before.clone();
569            before.focus(window, cx);
570        });
571        draw(cx);
572        cx.run_until_parked();
573        cx.update(|window, _| {
574            for index in 0..3 {
575                let header =
576                    test_support::find(window, &[], &format!("head-{index}").into()).unwrap();
577                let body =
578                    test_support::find(window, &[], &format!("body-{index}").into()).unwrap();
579                assert_eq!(header.bounds().origin.x, body.bounds().origin.x);
580                assert_eq!(header.bounds().size.width, body.bounds().size.width);
581                assert_eq!(header.role(), Some(Role::ColumnHeader));
582                assert_eq!(body.role(), Some(Role::Cell));
583                assert_eq!(body.focused(), None);
584                let expected = [90., 120., 240.][index];
585                assert_eq!(body.bounds().size.width, px(expected));
586            }
587            assert_eq!(
588                test_support::find(window, &[], &"head-0".into())
589                    .unwrap()
590                    .sort_direction(),
591                Some(SortDirection::Ascending),
592            );
593            assert_eq!(
594                test_support::find(window, &[], &"body-row".into())
595                    .unwrap()
596                    .selected(),
597                Some(true),
598            );
599        });
600        cx.simulate_keystrokes("tab");
601        draw(cx);
602        cx.update(|window, cx| assert!(view.read(cx).action.is_focused(window)));
603        let point = cx.update(|window, _| {
604            test_support::find(window, &[], &"table-action".into())
605                .unwrap()
606                .bounds()
607                .center()
608        });
609        cx.simulate_click(point, Modifiers::default());
610        draw(cx);
611        cx.update(|_, cx| assert_eq!(view.read(cx).clicks.get(), 1));
612        cx.simulate_keystrokes("tab");
613        draw(cx);
614        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
615    }
616}