A table with sortable columns, a text filter, row selection and pagination, generic over the row type.
use gpui::{div, prelude::*, px, Context, FontWeight, SharedString, Window};
use crate::ui::data_table::{DataColumn, DataTable, DataTableState};
use crate::ui::input::TextInput;
struct Payment {
id: &'static str,
amount: u32,
status: &'static str,
email: &'static str,
}
const PAYMENTS: [Payment; 8] = [
Payment { id: "m5gr84i9", amount: 316, status: "Success", email: "ken99@example.com" },
Payment { id: "3u1reuv4", amount: 242, status: "Success", email: "abe45@example.com" },
Payment { id: "derv1ws0", amount: 837, status: "Processing", email: "monserrat44@example.com" },
Payment { id: "5kma53ae", amount: 874, status: "Success", email: "silas22@example.com" },
Payment { id: "bhqecj4p", amount: 721, status: "Failed", email: "carmella@example.com" },
Payment { id: "p0x7c2rd", amount: 158, status: "Pending", email: "jamal71@example.com" },
Payment { id: "w8n3k1vz", amount: 590, status: "Success", email: "olivia.m@example.com" },
Payment { id: "q4t9h6ue", amount: 63, status: "Failed", email: "noah.b@example.com" },
];
#[derive(Default)]
pub struct PaymentsTable {
table: DataTableState,
}
impl Render for PaymentsTable {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Keyed state redraws this view whenever the input changes, so the rows re-filter as you type.
let filter = window.use_keyed_state("payments-filter", cx, |_, cx| {
TextInput::new(cx).placeholder("Filter emails...")
});
let table = DataTable::new(
"payments",
PAYMENTS,
|payment: &Payment| SharedString::from(payment.id),
self.table.clone(),
)
.selectable(true)
.page_size(4)
.filter(filter, |payment, query| {
payment.email.to_lowercase().contains(&query.to_lowercase())
})
.column(DataColumn::new("status", "Status", |payment: &Payment| payment.status).width(px(120.0)))
.column(
DataColumn::new("email", "Email", |payment: &Payment| payment.email)
.sort_by_key(|payment| payment.email),
)
.column(
DataColumn::new("amount", "Amount", |payment: &Payment| {
div().font_weight(FontWeight::MEDIUM).child(format!("${}.00", payment.amount))
})
.width(px(120.0))
.align_end()
.sort_by_key(|payment| payment.amount),
)
.on_change(cx.listener(|this, state: &DataTableState, _, cx| {
this.table = state.clone();
cx.notify();
}));
// A fixed height keeps the filter from jumping as the rows it matches shrink.
div().w(px(600.0)).h(px(296.0)).child(table)
}
}Installation
Copies src/ui/data_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.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/data_table.rs.src/ui/data_table.rs //! A data table with sortable columns, a text filter, row selection and pagination, built on //! `Table`. It is generic over your row type: each `DataColumn` says how to draw a cell and, //! optionally, how to compare two rows. use std::{cmp::Ordering, collections::BTreeSet, rc::Rc}; use gpui::{div, prelude::*, px, svg, AnyElement, App, ElementId, Entity, Pixels, SharedString, Window}; use crate::theme::ActiveTheme; use crate::ui::button::{Button, ButtonSize, ButtonVariant}; use crate::ui::checkbox::Checkbox; use crate::ui::input::TextInput; use crate::ui::table::{Table, TableColumn}; use crate::icons::{ARROW_DOWN, ARROW_UP, ARROW_UP_DOWN}; const SELECT_COLUMN_WIDTH: Pixels = px(40.0); /// A sort button's horizontal padding, pulled back out so its label lines up with the cells. const SORT_BUTTON_INSET: Pixels = px(-12.0); type ChangeHandler = Rc<dyn Fn(&DataTableState, &mut Window, &mut App) + 'static>; type Compare<R> = Rc<dyn Fn(&R, &R) -> Ordering + 'static>; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SortDirection { Ascending, Descending, } /// Everything about the table the user can change, except the filter text, which lives in the /// filter's `TextInput`. Keep one in your view and replace it in `on_change`. #[derive(Clone, Debug, PartialEq)] pub struct DataTableState { /// The id of the column rows are sorted by, and in which direction. pub sort: Option<(SharedString, SortDirection)>, /// The `row_key` of every selected row, including rows on other pages or filtered out. pub selected: BTreeSet<SharedString>, /// The current page, from 1. Clamped to the pages that exist when drawn. pub page: usize, } impl Default for DataTableState { fn default() -> Self { Self { sort: None, selected: BTreeSet::new(), page: 1, } } } /// How one column of `R` is drawn and sorted. pub struct DataColumn<R> { id: SharedString, header: SharedString, width: Option<Pixels>, align_end: bool, cell: Box<dyn Fn(&R) -> AnyElement + 'static>, compare: Option<Compare<R>>, } impl<R: 'static> DataColumn<R> { /// `id` names the column in `DataTableState::sort`; `cell` draws its value for one row. pub fn new<E: IntoElement>( id: impl Into<SharedString>, header: impl Into<SharedString>, cell: impl Fn(&R) -> E + 'static, ) -> Self { Self { id: id.into(), header: header.into(), width: None, align_end: false, cell: Box::new(move |row| cell(row).into_any_element()), compare: None, } } 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 } /// Makes the header a sort button that orders rows with `compare`. pub fn sort_by(mut self, compare: impl Fn(&R, &R) -> Ordering + 'static) -> Self { self.compare = Some(Rc::new(compare)); self } /// Makes the header a sort button that orders rows by `key`. pub fn sort_by_key<K: Ord>(self, key: impl Fn(&R) -> K + 'static) -> Self { self.sort_by(move |a, b| key(a).cmp(&key(b))) } } /// A controlled data table: the parent view owns a `DataTableState` and replaces it in /// `on_change`, and owns the filter's `TextInput` entity. #[derive(IntoElement)] pub struct DataTable<R: 'static> { id: ElementId, rows: Vec<R>, columns: Vec<DataColumn<R>>, row_key: Box<dyn Fn(&R) -> SharedString + 'static>, state: DataTableState, on_change: Option<ChangeHandler>, filter: Option<(Entity<TextInput>, Box<dyn Fn(&R, &str) -> bool + 'static>)>, selectable: bool, page_size: usize, empty: SharedString, } impl<R: 'static> DataTable<R> { /// `row_key` gives each row a stable identity, so selection survives sorting, filtering and /// paging. pub fn new( id: impl Into<ElementId>, rows: impl IntoIterator<Item = R>, row_key: impl Fn(&R) -> SharedString + 'static, state: DataTableState, ) -> Self { Self { id: id.into(), rows: rows.into_iter().collect(), columns: Vec::new(), row_key: Box::new(row_key), state, on_change: None, filter: None, selectable: false, page_size: 10, empty: "No results.".into(), } } pub fn column(mut self, column: DataColumn<R>) -> Self { self.columns.push(column); self } /// Shows `input` above the table and keeps the rows for which `matches(row, text)` holds. /// Create the input with `window.use_keyed_state`, or with `cx.new` plus a subscription to /// `InputEvent::Change` that calls `cx.notify()`, so your view redraws as the user types. pub fn filter(mut self, input: Entity<TextInput>, matches: impl Fn(&R, &str) -> bool + 'static) -> Self { self.filter = Some((input, Box::new(matches))); self } /// Adds a checkbox column. The header checkbox selects or clears the current page. pub fn selectable(mut self, selectable: bool) -> Self { self.selectable = selectable; self } /// Rows per page. 10 by default. pub fn page_size(mut self, page_size: usize) -> Self { self.page_size = page_size.max(1); self } /// Text shown when no row matches the filter. "No results." by default. pub fn empty(mut self, empty: impl Into<SharedString>) -> Self { self.empty = empty.into(); self } pub fn on_change(mut self, handler: impl Fn(&DataTableState, &mut Window, &mut App) + 'static) -> Self { self.on_change = Some(Rc::new(handler)); self } } impl<R: 'static> RenderOnce for DataTable<R> { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let (foreground, muted_foreground) = (theme.foreground, theme.muted_foreground); let state = self.state; let handler = self.on_change; // Every control hands the parent a copy of the state with one change applied. let emit = { let state = state.clone(); move |change: Box<dyn Fn(&mut DataTableState)>| { let (state, handler) = (state.clone(), handler.clone()); move |window: &mut Window, cx: &mut App| { if let Some(handler) = &handler { let mut next = state.clone(); change(&mut next); handler(&next, window, cx); } } } }; let query = self .filter .as_ref() .map(|(input, _)| input.read(cx).text()) .unwrap_or_default(); let mut visible: Vec<&R> = match &self.filter { Some((_, matches)) if !query.trim().is_empty() => self .rows .iter() .filter(|row| matches(row, query.trim())) .collect(), _ => self.rows.iter().collect(), }; let sort = state.sort.as_ref().and_then(|(id, direction)| { let column = self.columns.iter().find(|column| &column.id == id)?; Some((column.compare.clone()?, *direction)) }); if let Some((compare, direction)) = sort { visible.sort_by(|a, b| match direction { SortDirection::Ascending => compare(a, b), SortDirection::Descending => compare(b, a), }); } let filtered = visible.len(); let total_pages = filtered.div_ceil(self.page_size).max(1); let page = state.page.clamp(1, total_pages); let page_rows: Vec<&R> = visible .iter() .skip((page - 1) * self.page_size) .take(self.page_size) .copied() .collect(); let page_keys: Vec<SharedString> = page_rows.iter().map(|row| (self.row_key)(row)).collect(); let selected_count = visible .iter() .filter(|row| state.selected.contains(&(self.row_key)(row))) .count(); let mut table = Table::new(); let mut header: Vec<AnyElement> = Vec::new(); if self.selectable { table = table.column(TableColumn::new("").width(SELECT_COLUMN_WIDTH)); let all = !page_keys.is_empty() && page_keys.iter().all(|key| state.selected.contains(key)); let keys = page_keys.clone(); let toggle = emit(Box::new(move |state| { for key in &keys { if all { state.selected.remove(key); } else { state.selected.insert(key.clone()); } } })); header.push( Checkbox::new("select-all", all) .disabled(page_keys.is_empty()) .on_toggle(move |_, window, cx| toggle(window, cx)) .into_any_element(), ); } for column in &self.columns { let mut table_column = TableColumn::new(column.header.clone()); if let Some(width) = column.width { table_column = table_column.width(width); } if column.align_end { table_column = table_column.align_end(); } table = table.column(table_column); if column.compare.is_none() { header.push(column.header.clone().into_any_element()); continue; } let direction = state .sort .as_ref() .filter(|(id, _)| id == &column.id) .map(|(_, direction)| *direction); let icon = match direction { None => ARROW_UP_DOWN, Some(SortDirection::Ascending) => ARROW_UP, Some(SortDirection::Descending) => ARROW_DOWN, }; let id = column.id.clone(); // A second click flips the order; sorting starts over on the first page. let toggle = emit(Box::new(move |state| { let next = match direction { Some(SortDirection::Ascending) => SortDirection::Descending, _ => SortDirection::Ascending, }; state.sort = Some((id.clone(), next)); state.page = 1; })); let button = Button::new( ElementId::Name(format!("sort-{}", column.id).into()), column.header.clone(), ) .variant(ButtonVariant::Ghost) .size(ButtonSize::Sm) .trailing( svg() .data(icon) .flex_none() .size(px(16.0)) .text_color(if direction.is_some() { foreground } else { muted_foreground }), ) .on_click(move |_, window, cx| toggle(window, cx)); header.push( div() .map(|this| { if column.align_end { this.mr(SORT_BUTTON_INSET) } else { this.ml(SORT_BUTTON_INSET) } }) .child(button) .into_any_element(), ); } table = table.header(header); for (row, key) in page_rows.iter().zip(&page_keys) { let selected = state.selected.contains(key); let mut cells: Vec<AnyElement> = Vec::new(); if self.selectable { let id = ElementId::Name(format!("select-{key}").into()); let key = key.clone(); let toggle = emit(Box::new(move |state| { if !state.selected.remove(&key) { state.selected.insert(key.clone()); } })); cells.push( Checkbox::new(id, selected) .on_toggle(move |_, window, cx| toggle(window, cx)) .into_any_element(), ); } cells.extend(self.columns.iter().map(|column| (column.cell)(row))); table = if selected { table.selected_row(cells) } else { table.row(cells) }; } let empty = (filtered == 0).then(|| { div() .flex() .items_center() .justify_center() .h(px(96.0)) .text_sm() .text_color(foreground) .child(self.empty.clone()) }); let previous = emit(Box::new(move |state| state.page = page - 1)); let next = emit(Box::new(move |state| state.page = page + 1)); let footer = div() .flex() .items_center() .gap_2() .child( div() .flex_1() .text_sm() .text_color(muted_foreground) .when(self.selectable, |this| { this.child(format!("{selected_count} of {filtered} row(s) selected.")) }), ) .child( Button::new("previous", "Previous") .variant(ButtonVariant::Outline) .size(ButtonSize::Sm) .disabled(page <= 1) .on_click(move |_, window, cx| previous(window, cx)), ) .child( Button::new("next", "Next") .variant(ButtonVariant::Outline) .size(ButtonSize::Sm) .disabled(page >= total_pages) .on_click(move |_, window, cx| next(window, cx)), ); div() .id(self.id) .w_full() .flex() .flex_col() .gap_3() .when_some(self.filter.map(|(input, _)| input), |this, input| { this.child(div().w(px(384.0)).max_w_full().child(input)) }) .child( div() .rounded(theme.radius) .border_1() .border_color(theme.border) .overflow_hidden() .child(table) .children(empty), ) .child(footer) } }Register the module
// src/ui/mod.rs pub mod data_table;
Usage
use crate::ui::data_table::*;API Reference
SortDirection
SortDirection::AscendingSortDirection::DescendingDataColumn
How one column of R is drawn and sorted.
DataColumn::new<E: IntoElement>(id: impl Into<SharedString>, header: impl Into<SharedString>, cell: impl Fn(&R) -> E + 'static) -> Selfid names the column in DataTableState::sort; cell draws its value for one row.
.width(width: Pixels).align_end()Right-aligns the column, for numbers and amounts.
.sort_by(compare: impl Fn(&R, &R) -> Ordering + 'static)Makes the header a sort button that orders rows with compare.
DataColumn::sort_by_key<K: Ord>(self, key: impl Fn(&R) -> K + 'static) -> SelfMakes the header a sort button that orders rows by key.
DataTable
A controlled data table: the parent view owns a DataTableState and replaces it in on_change, and owns the filter's TextInput entity.
DataTable::new(id: impl Into<ElementId>, rows: impl IntoIterator<Item = R>, row_key: impl Fn(&R) -> SharedString + 'static, state: DataTableState) -> Selfrow_key gives each row a stable identity, so selection survives sorting, filtering and paging.
.column(column: DataColumn<R>).filter(input: Entity<TextInput>, matches: impl Fn(&R, &str) -> bool + 'static)Shows input above the table and keeps the rows for which matches(row, text) holds. Create the input with window.use_keyed_state, or with cx.new plus a subscription to InputEvent::Change that calls cx.notify(), so your view redraws as the user types.
.selectable(selectable: bool)Adds a checkbox column. The header checkbox selects or clears the current page.
.page_size(page_size: usize)Rows per page. 10 by default.
.empty(empty: impl Into<SharedString>)Text shown when no row matches the filter. "No results." by default.
.on_change(handler: impl Fn(&DataTableState, &mut Window, &mut App) + 'static)