Skip to main content

gpui_component/table/
table.rs

1use gpui::{
2    AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, Pixels,
3    RenderOnce, SharedString, StyleRefinement, Styled, TextAlign, Window, div,
4    prelude::FluentBuilder as _, px, relative,
5};
6use gpui_base::LogicalStyledExt as _;
7use gpui_base::{
8    Table as BaseTable, TableBody as BaseTableBody, TableCaption as BaseTableCaption,
9    TableCell as BaseTableCell, TableHead as BaseTableHead, TableHeader as BaseTableHeader,
10    TableRow as BaseTableRow,
11};
12
13use crate::{ActiveTheme as _, AnyChildElement, ChildElement, Sizable, Size, StyledExt as _};
14
15const MIN_CELL_WIDTH: Pixels = px(100.);
16
17/// A basic table component for directly rendering tabular data.
18///
19/// Unlike [`DataTable`], this is a simple, stateless, composable table
20/// without virtual scrolling or column management.
21///
22/// Size set via [`Sizable`] is automatically propagated to all children.
23///
24/// # Example
25///
26/// ```rust,ignore
27/// Table::new()
28///     .small()
29///     .child(TableHeader::new().child(
30///         TableRow::new()
31///             .child(TableHead::new().child("Name"))
32///             .child(TableHead::new().child("Email"))
33///     ))
34///     .child(TableBody::new()
35///         .child(TableRow::new()
36///             .child(TableCell::new().child("John"))
37///             .child(TableCell::new().child("john@example.com")))
38///     )
39///     .child(TableCaption::new().child("A list of recent invoices."))
40/// ```
41#[derive(IntoElement)]
42pub struct Table {
43    ix: usize,
44    style: StyleRefinement,
45    children: Vec<AnyChildElement>,
46    size: Size,
47    accessibility_label: Option<SharedString>,
48}
49
50impl Table {
51    pub fn new() -> Self {
52        Self {
53            ix: 0,
54            style: StyleRefinement::default(),
55            children: Vec::new(),
56            size: Size::default(),
57            accessibility_label: None,
58        }
59    }
60
61    /// Set the name a screen reader announces for the table.
62    ///
63    /// A [`TableCaption`] is visible descriptive content and is not used
64    /// automatically as the table's accessible name.
65    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
66        self.accessibility_label = Some(label.into());
67        self
68    }
69
70    pub fn child(mut self, child: impl ChildElement + 'static) -> Self {
71        self.children.push(AnyChildElement::new(child));
72        self
73    }
74
75    pub fn children<E: ChildElement + 'static>(
76        mut self,
77        children: impl IntoIterator<Item = E>,
78    ) -> Self {
79        self.children
80            .extend(children.into_iter().map(AnyChildElement::new));
81        self
82    }
83}
84
85impl Styled for Table {
86    fn style(&mut self) -> &mut StyleRefinement {
87        &mut self.style
88    }
89}
90
91impl Sizable for Table {
92    fn with_size(mut self, size: impl Into<Size>) -> Self {
93        self.size = size.into();
94        self
95    }
96}
97
98impl ChildElement for Table {
99    fn with_ix(mut self, ix: usize) -> Self {
100        self.ix = ix;
101        self
102    }
103}
104
105impl RenderOnce for Table {
106    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
107        BaseTable::new(("table", self.ix))
108            .when_some(self.accessibility_label, |this, label| {
109                this.accessibility_label(label)
110            })
111            .w_full()
112            .text_sm()
113            .overflow_hidden()
114            .bg(cx.theme().tokens.table)
115            .refine_style(&self.style)
116            .children(
117                self.children
118                    .into_iter()
119                    .enumerate()
120                    .map(|(ix, c)| c.into_any(ix, self.size)),
121            )
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    #[test]
130    fn stores_an_explicit_accessibility_label() {
131        let plain = Table::new();
132        assert_eq!(plain.accessibility_label, None);
133
134        let named = Table::new().accessibility_label("Recent invoices");
135        assert_eq!(
136            named.accessibility_label.as_deref(),
137            Some("Recent invoices")
138        );
139    }
140
141    #[test]
142    fn stores_a_row_hover_style() {
143        assert!(TableRow::new().hover_style.is_none());
144
145        let row = TableRow::new().hover(|this| this.opacity(0.5));
146        assert_eq!(row.hover_style.and_then(|style| style.opacity), Some(0.5));
147    }
148
149    #[test]
150    fn stores_an_explicit_row_id() {
151        assert_eq!(TableRow::new().id, None);
152        assert_eq!(
153            TableRow::new().id("alice").id,
154            Some(ElementId::from("alice"))
155        );
156    }
157}
158
159/// The header section of a [`Table`], wrapping header rows.
160#[derive(IntoElement)]
161pub struct TableHeader {
162    ix: usize,
163    style: StyleRefinement,
164    children: Vec<AnyChildElement>,
165    size: Size,
166}
167
168impl TableHeader {
169    pub fn new() -> Self {
170        Self {
171            ix: 0,
172            style: StyleRefinement::default(),
173            children: Vec::new(),
174            size: Size::default(),
175        }
176    }
177
178    pub fn child(mut self, child: impl ChildElement + 'static) -> Self {
179        self.children.push(AnyChildElement::new(child));
180        self
181    }
182
183    pub fn children<E: ChildElement + 'static>(
184        mut self,
185        children: impl IntoIterator<Item = E>,
186    ) -> Self {
187        self.children
188            .extend(children.into_iter().map(AnyChildElement::new));
189        self
190    }
191}
192
193impl Styled for TableHeader {
194    fn style(&mut self) -> &mut StyleRefinement {
195        &mut self.style
196    }
197}
198
199impl ChildElement for TableHeader {
200    fn with_ix(mut self, ix: usize) -> Self {
201        self.ix = ix;
202        self
203    }
204}
205
206impl Sizable for TableHeader {
207    fn with_size(mut self, size: impl Into<Size>) -> Self {
208        self.size = size.into();
209        self
210    }
211}
212
213impl RenderOnce for TableHeader {
214    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
215        BaseTableHeader::new(("table-header", self.ix))
216            .w_full()
217            .bg(cx.theme().tokens.table_head)
218            .text_color(cx.theme().table_head_foreground)
219            .refine_style(&self.style)
220            .border_b_1()
221            .border_color(cx.theme().table_row_border)
222            .children(
223                self.children
224                    .into_iter()
225                    .enumerate()
226                    .map(|(ix, c)| c.into_any(ix, self.size)),
227            )
228    }
229}
230
231/// The body section of a [`Table`], wrapping data rows.
232#[derive(IntoElement)]
233pub struct TableBody {
234    ix: usize,
235    style: StyleRefinement,
236    children: Vec<AnyChildElement>,
237    size: Size,
238}
239
240impl TableBody {
241    pub fn new() -> Self {
242        Self {
243            ix: 0,
244            style: StyleRefinement::default(),
245            children: Vec::new(),
246            size: Size::default(),
247        }
248    }
249
250    pub fn child(mut self, child: impl ChildElement + 'static) -> Self {
251        self.children.push(AnyChildElement::new(child));
252        self
253    }
254
255    pub fn children<E: ChildElement + 'static>(
256        mut self,
257        children: impl IntoIterator<Item = E>,
258    ) -> Self {
259        self.children
260            .extend(children.into_iter().map(AnyChildElement::new));
261        self
262    }
263}
264
265impl Styled for TableBody {
266    fn style(&mut self) -> &mut StyleRefinement {
267        &mut self.style
268    }
269}
270
271impl Sizable for TableBody {
272    fn with_size(mut self, size: impl Into<Size>) -> Self {
273        self.size = size.into();
274        self
275    }
276}
277
278impl ChildElement for TableBody {
279    fn with_ix(mut self, ix: usize) -> Self {
280        self.ix = ix;
281        self
282    }
283}
284
285impl RenderOnce for TableBody {
286    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
287        BaseTableBody::new(("table-body", self.ix))
288            .w_full()
289            .refine_style(&self.style)
290            .children(
291                self.children
292                    .into_iter()
293                    .enumerate()
294                    .map(|(ix, c)| c.into_any(ix, self.size)),
295            )
296    }
297}
298
299/// The footer section of a [`Table`], wrapping footer rows.
300#[derive(IntoElement)]
301pub struct TableFooter {
302    ix: usize,
303    style: StyleRefinement,
304    children: Vec<AnyChildElement>,
305    size: Size,
306}
307
308impl TableFooter {
309    pub fn new() -> Self {
310        Self {
311            ix: 0,
312            style: StyleRefinement::default(),
313            children: Vec::new(),
314            size: Size::default(),
315        }
316    }
317
318    pub fn child(mut self, child: impl ChildElement + 'static) -> Self {
319        self.children.push(AnyChildElement::new(child));
320        self
321    }
322
323    pub fn children<E: ChildElement + 'static>(
324        mut self,
325        children: impl IntoIterator<Item = E>,
326    ) -> Self {
327        self.children
328            .extend(children.into_iter().map(AnyChildElement::new));
329        self
330    }
331}
332
333impl Styled for TableFooter {
334    fn style(&mut self) -> &mut StyleRefinement {
335        &mut self.style
336    }
337}
338
339impl Sizable for TableFooter {
340    fn with_size(mut self, size: impl Into<Size>) -> Self {
341        self.size = size.into();
342        self
343    }
344}
345
346impl ChildElement for TableFooter {
347    fn with_ix(mut self, ix: usize) -> Self {
348        self.ix = ix;
349        self
350    }
351}
352
353impl RenderOnce for TableFooter {
354    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
355        div()
356            .id(("table-footer", self.ix))
357            .w_full()
358            .bg(cx.theme().tokens.table_foot)
359            .text_color(cx.theme().table_foot_foreground)
360            .border_t_1()
361            .border_color(cx.theme().table_row_border)
362            .refine_style(&self.style)
363            .children(
364                self.children
365                    .into_iter()
366                    .enumerate()
367                    .map(|(ix, c)| c.into_any(ix, self.size)),
368            )
369    }
370}
371
372/// A row in a [`Table`].
373#[derive(IntoElement)]
374pub struct TableRow {
375    id: Option<ElementId>,
376    ix: usize,
377    style: StyleRefinement,
378    hover_style: Option<Box<StyleRefinement>>,
379    children: Vec<AnyChildElement>,
380    size: Size,
381}
382
383impl TableRow {
384    pub fn new() -> Self {
385        Self {
386            id: None,
387            ix: 0,
388            style: StyleRefinement::default(),
389            hover_style: None,
390            children: Vec::new(),
391            size: Size::default(),
392        }
393    }
394
395    /// Apply the given style to the row while the pointer is over it, such as
396    /// `.hover(|this| this.bg(cx.theme().table_hover))`.
397    pub fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
398        self.hover_style = Some(Box::new(f(StyleRefinement::default())));
399        self
400    }
401
402    /// Set a stable identity for the row. Without one a row is identified by
403    /// its position, so element state inside it (an open popover, a tooltip)
404    /// stays at that position when the rows reorder.
405    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
406        self.id = Some(id.into());
407        self
408    }
409
410    pub fn child(mut self, child: impl ChildElement + 'static) -> Self {
411        self.children.push(AnyChildElement::new(child));
412        self
413    }
414
415    pub fn children<E: ChildElement + 'static>(
416        mut self,
417        children: impl IntoIterator<Item = E>,
418    ) -> Self {
419        self.children
420            .extend(children.into_iter().map(AnyChildElement::new));
421        self
422    }
423}
424
425impl Styled for TableRow {
426    fn style(&mut self) -> &mut StyleRefinement {
427        &mut self.style
428    }
429}
430
431impl Sizable for TableRow {
432    fn with_size(mut self, size: impl Into<Size>) -> Self {
433        self.size = size.into();
434        self
435    }
436}
437
438impl ChildElement for TableRow {
439    fn with_ix(mut self, ix: usize) -> Self {
440        self.ix = ix;
441        self
442    }
443}
444
445impl RenderOnce for TableRow {
446    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
447        let id = self.id.unwrap_or_else(|| ("table-row", self.ix).into());
448        BaseTableRow::new(id, self.ix + 1)
449            .w_full()
450            .flex_row_dir(cx)
451            .refine_style(&self.style)
452            .border_color(cx.theme().table_row_border)
453            .when(self.ix > 0, |this| this.border_t_1())
454            .when_some(self.hover_style, |this, style| this.hover(move |_| *style))
455            .children(
456                self.children
457                    .into_iter()
458                    .enumerate()
459                    .map(|(ix, c)| c.into_any(ix, self.size)),
460            )
461    }
462}
463
464/// A header cell in a [`TableRow`].
465#[derive(IntoElement)]
466pub struct TableHead {
467    ix: usize,
468    style: StyleRefinement,
469    children: Vec<AnyElement>,
470    col_span: usize,
471    align: TextAlign,
472    size: Size,
473}
474
475impl TableHead {
476    pub fn new() -> Self {
477        Self {
478            ix: 0,
479            style: StyleRefinement::default(),
480            children: Vec::new(),
481            col_span: 1,
482            align: TextAlign::Left,
483            size: Size::default(),
484        }
485    }
486
487    /// Set the column span of this header cell.
488    pub fn col_span(mut self, span: usize) -> Self {
489        self.col_span = span.max(1);
490        self
491    }
492
493    /// Set text alignment to center.
494    pub fn text_center(mut self) -> Self {
495        self.align = TextAlign::Center;
496        self
497    }
498
499    /// Set text alignment to right.
500    pub fn text_right(mut self) -> Self {
501        self.align = TextAlign::Right;
502        self
503    }
504}
505
506impl ParentElement for TableHead {
507    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
508        self.children.extend(elements);
509    }
510}
511
512impl Sizable for TableHead {
513    fn with_size(mut self, size: impl Into<Size>) -> Self {
514        self.size = size.into();
515        self
516    }
517}
518
519impl ChildElement for TableHead {
520    fn with_ix(mut self, ix: usize) -> Self {
521        self.ix = ix;
522        self
523    }
524}
525
526impl Styled for TableHead {
527    fn style(&mut self) -> &mut StyleRefinement {
528        &mut self.style
529    }
530}
531
532impl RenderOnce for TableHead {
533    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
534        let paddings = self.size.table_cell_padding();
535
536        BaseTableHead::new(("table-head", self.ix), self.ix + 1)
537            .flex_row_dir(cx)
538            .items_center()
539            .when(self.style.size.width.is_none(), |this| {
540                this.flex_shrink_1()
541                    .flex_basis(relative(self.col_span as f32))
542            })
543            .min_w(MIN_CELL_WIDTH * self.col_span)
544            .px(paddings.left)
545            .py(paddings.top)
546            .when(self.align == TextAlign::Center, |this| {
547                this.justify_center()
548            })
549            .when(self.align == TextAlign::Right, |this| {
550                this.justify_flex_end()
551            })
552            .refine_style(&self.style)
553            .children(self.children)
554    }
555}
556
557/// A data cell in a [`TableRow`].
558#[derive(IntoElement)]
559pub struct TableCell {
560    ix: usize,
561    style: StyleRefinement,
562    children: Vec<AnyElement>,
563    col_span: usize,
564    align: TextAlign,
565    size: Size,
566}
567
568impl TableCell {
569    pub fn new() -> Self {
570        Self {
571            ix: 0,
572            style: StyleRefinement::default(),
573            children: Vec::new(),
574            col_span: 1,
575            align: TextAlign::Left,
576            size: Size::default(),
577        }
578    }
579
580    /// Set the column span of this cell.
581    pub fn col_span(mut self, span: usize) -> Self {
582        self.col_span = span.max(1);
583        self
584    }
585
586    /// Set text alignment to center.
587    pub fn text_center(mut self) -> Self {
588        self.align = TextAlign::Center;
589        self
590    }
591
592    /// Set text alignment to right.
593    pub fn text_right(mut self) -> Self {
594        self.align = TextAlign::Right;
595        self
596    }
597}
598
599impl ParentElement for TableCell {
600    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
601        self.children.extend(elements);
602    }
603}
604
605impl Sizable for TableCell {
606    fn with_size(mut self, size: impl Into<Size>) -> Self {
607        self.size = size.into();
608        self
609    }
610}
611
612impl ChildElement for TableCell {
613    fn with_ix(mut self, ix: usize) -> Self {
614        self.ix = ix;
615        self
616    }
617}
618
619impl Styled for TableCell {
620    fn style(&mut self) -> &mut StyleRefinement {
621        &mut self.style
622    }
623}
624
625impl RenderOnce for TableCell {
626    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
627        let paddings = self.size.table_cell_padding();
628
629        BaseTableCell::new(("table-cell", self.ix), self.ix + 1)
630            .flex_row_dir(cx)
631            .items_center()
632            .when(self.style.size.width.is_none(), |this| {
633                this.flex_shrink_1()
634                    .flex_basis(relative(self.col_span as f32))
635            })
636            .min_w(MIN_CELL_WIDTH * self.col_span)
637            .px(paddings.left)
638            .py(paddings.top)
639            .when(self.align == TextAlign::Center, |this| {
640                this.justify_center()
641            })
642            .when(self.align == TextAlign::Right, |this| {
643                this.justify_flex_end()
644            })
645            .refine_style(&self.style)
646            .children(self.children)
647    }
648}
649
650/// A caption displayed below the [`Table`].
651#[derive(IntoElement)]
652pub struct TableCaption {
653    ix: usize,
654    style: StyleRefinement,
655    children: Vec<AnyElement>,
656    size: Size,
657}
658
659impl TableCaption {
660    pub fn new() -> Self {
661        Self {
662            ix: 0,
663            style: StyleRefinement::default(),
664            children: Vec::new(),
665            size: Size::default(),
666        }
667    }
668}
669
670impl ParentElement for TableCaption {
671    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
672        self.children.extend(elements);
673    }
674}
675
676impl Sizable for TableCaption {
677    fn with_size(mut self, size: impl Into<Size>) -> Self {
678        self.size = size.into();
679        self
680    }
681}
682
683impl ChildElement for TableCaption {
684    fn with_ix(mut self, ix: usize) -> Self {
685        self.ix = ix;
686        self
687    }
688}
689
690impl Styled for TableCaption {
691    fn style(&mut self) -> &mut StyleRefinement {
692        &mut self.style
693    }
694}
695
696impl RenderOnce for TableCaption {
697    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
698        let paddings = self.size.table_cell_padding();
699
700        BaseTableCaption::new(("table-caption", self.ix))
701            .w_full()
702            .px(paddings.left)
703            .py(paddings.top)
704            .text_sm()
705            .text_color(cx.theme().muted_foreground)
706            .text_center()
707            .refine_style(&self.style)
708            .children(self.children)
709    }
710}