A static data table with a header, body rows, an optional footer and caption.
use gpui::{div, prelude::*, px};
use crate::ui::table::{Table, TableColumn};
const INVOICES: [[&str; 4]; 4] = [
["INV001", "Paid", "Credit Card", "$250.00"],
["INV002", "Pending", "PayPal", "$150.00"],
["INV003", "Unpaid", "Bank Transfer", "$350.00"],
["INV004", "Paid", "Credit Card", "$450.00"],
];
pub fn table_demo() -> impl IntoElement {
let table = Table::new().id("table-demo")
.column(TableColumn::new("Invoice").width(px(100.0)))
.column(TableColumn::new("Status"))
.column(TableColumn::new("Method"))
.column(TableColumn::new("Amount").align_end());
div().w(px(520.0)).child(
INVOICES
.into_iter()
.fold(table, |table, invoice| table.row(invoice))
.footer(["Total", "", "", "$1,200.00"])
.caption("A list of your recent invoices."),
)
}Installation
Copies src/ui/table.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/table.rs.src/ui/table.rs use std::sync::Arc; use gpui::{ div, prelude::*, px, AnimationExt, AnyElement, App, Div, ElementId, FontWeight, Pixels, SharedString, SpringAnimation, SpringConfig, Window, }; use crate::theme::ActiveTheme; /// Stands in for shadcn's `transition-colors` (150ms) on the row hover: critically damped /// (damping = 2 * sqrt(stiffness)), so the tint eases in and out without flicker. const HOVER_SPRING: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); /// A column's header and how its cells are laid out. GPUI has no table layout, so every /// cell in a column takes the same width and alignment from here. pub struct TableColumn { header: SharedString, width: Option<Pixels>, align_end: bool, } impl TableColumn { /// A column that shares the leftover width with the other flexible columns. pub fn new(header: impl Into<SharedString>) -> Self { Self { header: header.into(), width: None, align_end: false, } } pub fn width(mut self, width: Pixels) -> Self { self.width = Some(width); self } /// Right-aligns the column, for numbers and amounts. pub fn align_end(mut self) -> Self { self.align_end = true; self } } /// A static data table: a header row, body rows, an optional footer row and caption. #[derive(IntoElement)] pub struct Table { id: Option<ElementId>, columns: Vec<TableColumn>, header: Option<Vec<AnyElement>>, /// Each row's cells and whether it is drawn selected. rows: Vec<(Vec<AnyElement>, bool)>, footer: Option<Vec<AnyElement>>, caption: Option<SharedString>, } impl Table { pub fn new() -> Self { Self { id: None, columns: Vec::new(), header: None, rows: Vec::new(), footer: None, caption: None, } } /// Fades the row hover tint in and out, like shadcn's `transition-colors`, instead of /// switching it. The id keeps each row's hover state between renders, so it must be unique /// among the tables on screen. Without one the tint switches at once. pub fn id(mut self, id: impl Into<ElementId>) -> Self { self.id = Some(id.into()); self } pub fn column(mut self, column: TableColumn) -> Self { self.columns.push(column); self } /// One cell per column. Extra cells are dropped; missing ones are left blank. pub fn row<E: IntoElement>(mut self, cells: impl IntoIterator<Item = E>) -> Self { self.rows.push((cells.into_iter().map(IntoElement::into_any_element).collect(), false)); self } /// A row drawn with the muted background shadcn/ui gives selected rows. pub fn selected_row<E: IntoElement>(mut self, cells: impl IntoIterator<Item = E>) -> Self { self.rows.push((cells.into_iter().map(IntoElement::into_any_element).collect(), true)); self } /// Header cells to show instead of the column titles, e.g. sort buttons or a select-all /// checkbox. Widths and alignment still come from the columns. pub fn header<E: IntoElement>(mut self, cells: impl IntoIterator<Item = E>) -> Self { self.header = Some(cells.into_iter().map(IntoElement::into_any_element).collect()); self } /// A summary row under the body, e.g. totals. Pass `""` for cells to leave blank. pub fn footer<E: IntoElement>(mut self, cells: impl IntoIterator<Item = E>) -> Self { self.footer = Some(cells.into_iter().map(IntoElement::into_any_element).collect()); self } /// A short description shown below the table. pub fn caption(mut self, caption: impl Into<SharedString>) -> Self { self.caption = Some(caption.into()); self } } impl RenderOnce for Table { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let (border, row_hover, selected_bg, fg, muted_fg) = { let theme = cx.theme(); (theme.border, theme.muted.opacity(0.5), theme.muted, theme.foreground, theme.muted_foreground) }; let columns = self.columns; let cell = |ix: usize| -> Div { let column = columns.get(ix); div() .flex() .items_center() .min_w_0() .px_2() .map(|this| match column.and_then(|c| c.width) { Some(width) => this.flex_none().w(width), None => this.flex_1().flex_basis(px(0.0)), }) .when(column.is_some_and(|c| c.align_end), |this| this.justify_end()) }; let line = |cells: Vec<AnyElement>, height: Pixels| { let mut cells = cells.into_iter(); div() .flex() .h(height) .children((0..columns.len()).map(|ix| cell(ix).children(cells.next()))) }; let header = match self.header { Some(cells) => line(cells, px(40.0)), None => line( columns.iter().map(|column| column.header.clone().into_any_element()).collect(), px(40.0), ), } .border_b_1() .border_color(border) .font_weight(FontWeight::MEDIUM); // The last body row only keeps its rule when a footer follows it. let last = self.rows.len().saturating_sub(1); let has_footer = self.footer.is_some(); let id = self.id; let rows: Vec<AnyElement> = self .rows .into_iter() .enumerate() .map(|(ix, (cells, selected))| { let row = line(cells, px(40.0)) .when(ix != last || has_footer, |this| this.border_b_1().border_color(border)); // Selected rows keep their fill; hovering them doesn't change it. if selected { return row.bg(selected_bg).into_any_element(); } let Some(id) = &id else { return row.hover(move |style| style.bg(row_hover)).into_any_element(); }; let child_id = |name: String| ElementId::NamedChild(Arc::new(id.clone()), name.into()); let hovered = window.use_keyed_state(child_id(format!("row-hovered-{ix}")), cx, |_, _| false); let is_hovered = *hovered.read(cx); row.id(child_id(format!("row-{ix}"))) .on_hover(move |over, _, cx| { hovered.update(cx, |hovered, cx| { *hovered = *over; cx.notify(); }) }) .with_spring( child_id(format!("row-tint-{ix}")), SpringAnimation::new(HOVER_SPRING).to(is_hovered), move |this, phase| { this.bg(row_hover.opacity(phase.interpolate_clamped(0.0, 1.0))) }, ) .into_any_element() }) .collect(); let footer = self.footer.map(|cells| { line(cells, px(40.0)) .bg(row_hover) .font_weight(FontWeight::MEDIUM) }); div() .w_full() .flex() .flex_col() .text_sm() .text_color(fg) .child(header) .children(rows) .children(footer) .when_some(self.caption, |this, caption| { this.child( div() .mt_4() .text_center() .text_color(muted_fg) .child(caption), ) }) } }Register the module
// src/ui/mod.rs pub mod table;
Usage
use crate::ui::table::*;Examples
Footer
footer adds a summary row under the body, such as a total. Pass "" for cells to leave blank.
use gpui::{div, prelude::*, px};
use crate::ui::table::{Table, TableColumn};
const INVOICES: [[&str; 4]; 3] = [
["INV001", "Paid", "Credit Card", "$250.00"],
["INV002", "Pending", "PayPal", "$150.00"],
["INV003", "Unpaid", "Bank Transfer", "$2,100.00"],
];
pub fn table_footer() -> impl IntoElement {
let table = Table::new().id("table-footer")
.column(TableColumn::new("Invoice").width(px(100.0)))
.column(TableColumn::new("Status"))
.column(TableColumn::new("Method"))
.column(TableColumn::new("Amount").align_end());
div().w(px(520.0)).child(
INVOICES
.into_iter()
.fold(table, |table, invoice| table.row(invoice))
.footer(["Total", "", "", "$2,500.00"]),
)
}Actions
Cells take any element, so a row can end in a DropdownMenu of actions. The view tracks which row's menu is open.
use gpui::{div, prelude::*, px, svg, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::ui::popover::Align;
use crate::ui::table::{Table, TableColumn};
use crate::icons::ELLIPSIS;
const PRODUCTS: [(&str, &str); 3] = [
("Wireless Mouse", "$29.99"),
("Mechanical Keyboard", "$129.99"),
("USB-C Hub", "$49.99"),
];
#[derive(Default)]
pub struct TableActions {
open: Option<usize>,
}
impl Render for TableActions {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme().clone();
let accent = theme.accent;
let mut table = Table::new().id("table-actions")
.column(TableColumn::new("Product"))
.column(TableColumn::new("Price").width(px(110.0)).align_end())
.column(TableColumn::new("").width(px(52.0)).align_end());
for (ix, (product, price)) in PRODUCTS.into_iter().enumerate() {
let trigger = div()
.id(("table-actions-trigger", ix))
.size(px(32.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.cursor_pointer()
.hover(move |style| style.bg(accent))
.child(svg().data(ELLIPSIS).size(px(16.0)).text_color(theme.foreground));
let menu = DropdownMenu::new(("table-actions-menu", ix), self.open == Some(ix))
.trigger(trigger)
.align(Align::End)
.width(px(160.0))
.on_open_change(cx.listener(move |this, open: &bool, _, cx| {
this.open = open.then_some(ix);
cx.notify();
}))
.item(MenuItem::new("Edit"))
.item(MenuItem::new("Duplicate"))
.separator()
.item(MenuItem::new("Delete").destructive(true));
table = table.row([
div().child(product).into_any_element(),
div().child(price).into_any_element(),
menu.into_any_element(),
]);
}
// Top-aligned so the menus have room to open downward in the preview.
div().h(px(300.0)).w(px(440.0)).child(table)
}
}API Reference
TableColumn
A column's header and how its cells are laid out. GPUI has no table layout, so every cell in a column takes the same width and alignment from here.
TableColumn::new(header: impl Into<SharedString>) -> SelfA column that shares the leftover width with the other flexible columns.
.width(width: Pixels).align_end()Right-aligns the column, for numbers and amounts.
Table
A static data table: a header row, body rows, an optional footer row and caption.
Table::new() -> Self.id(id: impl Into<ElementId>)Fades the row hover tint in and out, like shadcn's transition-colors, instead of switching it. The id keeps each row's hover state between renders, so it must be unique among the tables on screen. Without one the tint switches at once.
.column(column: TableColumn)Table::row<E: IntoElement>(mut self, cells: impl IntoIterator<Item = E>) -> SelfOne cell per column. Extra cells are dropped; missing ones are left blank.
Table::selected_row<E: IntoElement>(mut self, cells: impl IntoIterator<Item = E>) -> SelfA row drawn with the muted background shadcn/ui gives selected rows.
Table::header<E: IntoElement>(mut self, cells: impl IntoIterator<Item = E>) -> SelfHeader cells to show instead of the column titles, e.g. sort buttons or a select-all checkbox. Widths and alignment still come from the columns.
Table::footer<E: IntoElement>(mut self, cells: impl IntoIterator<Item = E>) -> SelfA summary row under the body, e.g. totals. Pass "" for cells to leave blank.
.caption(caption: impl Into<SharedString>)A short description shown below the table.