Table
A data table: sticky header, sortable, resizable, movable and fixed columns, row selection, dragging and dropping rows, a footer, cell editing over virtualised rows and a toolbar attached on top.
Data table
ui.vertical(|ui| {
ui.horizontal(|ui| {
for name in ["Everything", "Compact"] {
let chosen = state
.presets
.matching(&state.shown)
.map(|preset| preset.name.as_str());
if ui
.add(Button::new(name).small().selected(chosen == Some(name)))
.clicked()
{
state.shown = state.presets.choose(name).unwrap_or_default();
}
}
if ui.add(Button::new("Refresh plays").small()).clicked() {
// New data arrives: the order shown stays, and the
// sorted column offers Sort again.
state.refreshes += 1;
for track in &mut state.tracks {
track.plays = (track.plays * 7 + state.refreshes * 13 + track.id) % 500;
}
state
.order
.refresh(&sorted_ids(&state.tracks, &state.table));
}
});
let all = columns();
let shown: Vec<Column<'_>> = state
.shown
.iter()
.filter_map(|key| all.iter().find(|column| column.key() == key).cloned())
.collect();
let mut library = Library {
tracks: &mut state.tracks,
order: state.order.ids(),
draft: &mut state.draft,
focus_draft: &mut state.focus_draft,
committed: false,
};
let response = Table::new(&mut state.table, &shown)
.id_salt("library")
.stripe(true)
.multi_select(true)
.stale_sort(state.order.is_stale())
.max_height(360.0)
.accessibility_label("Library")
.show(ui, &mut library);
if library.committed {
state.table.editing = None;
}
if let Some((row, _)) = response.edit_started {
let id = state.order.ids()[row] as usize;
state.draft = state.tracks[id].note.clone();
state.focus_draft = true;
}
if response.sort_changed || response.sort_again {
state.order = StableOrder::sorted(sorted_ids(&state.tracks, &state.table));
}
let sort = state.table.sort.as_ref().map_or("none".to_owned(), |sort| {
let way = if sort.sort == ColumnSort::Ascending {
"up"
} else {
"down"
};
format!("{} {way}", sort.column)
});
ui.label(format!(
"{} selected, sorted by {sort}",
state.table.selection.len()
));
});
Moving columns and rows
ui.vertical(|ui| {
ui.label("Drag a header to move its column, and rows to reorder them or onto the playlist. Artist hides in a narrow table. A row under the pointer shows its heart.");
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(420.0);
let columns = [
Column::new("loved", "Loved").width(44.0).resizable(false),
Column::new("title", "Title").width(180.0).fill(),
Column::new("artist", "Artist").width(140.0).hide_below(360.0),
];
let response = Table::new(&mut state.queue_table, &columns)
.id_salt("queue")
.multi_select(true)
.reorder_columns(true)
.drag_rows(true)
.drop_between_rows(true)
.show(ui, &mut Queue { songs: &mut state.queue });
if let Some(index) = response.dropped
&& let Some(rows) = egui::DragAndDrop::take_payload::<TableRows>(ui.ctx())
&& rows.table == response.response.id
{
move_songs(&mut state.queue, &rows.rows, index);
}
});
let (rect, target) =
ui.allocate_exact_size(egui::vec2(180.0, 120.0), egui::Sense::hover());
let theme = tokens(ui.ctx());
ui.painter().rect_stroke(
rect,
theme.shape.radius,
egui::Stroke::new(1.0, theme.border),
egui::StrokeKind::Inside,
);
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
format!("Playlist\n{} songs", state.playlist.len()),
egui::FontId::proportional(14.0),
theme.foreground,
);
if let Some(rows) = target.drop_target::<TableRows>(ui) {
state.playlist.extend(&rows.keys);
}
});
});
A style of the app’s own
/// TonePush's library, as a table style: a chevron after a sorted
/// column's title and a rounded wash behind a header under the pointer,
/// a firmer line under the header, the tone playing filled and
/// outlined in amber, a translucent wash under the pointer, and
/// scrollbars as wide as the app's egui scroll style draws them.
struct Amp;
/// The amber TonePush keeps for the tone playing.
const AMBER: egui::Color32 = egui::Color32::from_rgb(0xe0, 0x9a, 0x2c);
impl TableStyle for Amp {
fn paint_row(&self, row: &TableRowConfiguration<'_>) {
let theme = row.theme;
let fill = if row.state.current {
AMBER.gamma_multiply(0.16)
} else if row.state.selected {
theme.table.hover
} else if row.state.hovered {
theme.table.hover.gamma_multiply(0.45)
} else {
egui::Color32::TRANSPARENT
};
row.paint_fill(fill);
row.paint_divider(theme.table.row_border);
if row.state.current {
row.paint_outline(egui::Stroke::new(1.0, AMBER.gamma_multiply(0.7)));
}
}
fn paint_header(&self, header: &TableHeaderConfiguration<'_>) {
let theme = header.theme;
if header.sortable && header.state.hovered {
header.painter().rect_filled(
header.rect.shrink2(egui::vec2(2.0, 4.0)),
6.0,
theme.table.hover.gamma_multiply(0.6),
);
}
let sorted = header.sort != ColumnSort::None;
let color = if sorted {
theme.foreground
} else {
theme.muted_foreground
};
header.paint_title(Some(color));
if let Some(title) = header.title
&& sorted
{
let icon = if header.sort == ColumnSort::Ascending {
Icon::ChevronUp
} else {
Icon::ChevronDown
};
let center = egui::pos2(title.right() + 9.0, header.rect.center().y);
icon.paint(
header.painter(),
egui::Rect::from_center_size(center, egui::Vec2::splat(12.0)),
color,
);
}
}
fn paint_header_divider(
&self,
painter: &egui::Painter,
theme: &fastframe_ui::Tokens,
rect: egui::Rect,
) {
painter.hline(
rect.x_range(),
rect.bottom() - 0.5,
egui::Stroke::new(1.0, theme.border),
);
}
fn paint_scrollbar(&self, bar: &TableScrollbar<'_>) {
// As wide as egui's own floating bars: thin at rest, wide
// under the pointer, near the table's edge.
let scroll = bar.painter().ctx().global_style().spacing.scroll;
let wide = bar.state.hovered || bar.state.pressed;
let width = if wide {
scroll.bar_width
} else {
scroll.floating_width.max(4.0)
};
let thumb = if bar.vertical {
let right = bar.track.right() - 2.0;
egui::Rect::from_x_y_ranges(right - width..=right, bar.thumb.y_range())
} else {
let bottom = bar.track.bottom() - 2.0;
egui::Rect::from_x_y_ranges(bar.thumb.x_range(), bottom - width..=bottom)
};
let color = if wide {
bar.theme.scrollbar.thumb_hover
} else {
bar.theme.scrollbar.thumb
};
bar.painter()
.rect_filled(thumb, width / 2.0, color.gamma_multiply(bar.opacity));
}
}
/// A row of the library: a group's caption and how many tones it
/// has, or a tone.
#[derive(Clone, Copy)]
enum Row {
Group(&'static str, usize),
Tone(usize),
}
impl Row {
/// The key of this row, at `row` in the order shown.
fn key(self, row: usize) -> u64 {
match self {
Self::Group(..) => u64::MAX - row as u64,
Self::Tone(tone) => tone as u64,
}
}
}
/// The tones in groups, in the order shown, one of them playing
/// and the ones the story selected.
struct Tones<'a> {
playing: Option<u64>,
selected: &'a Selection,
names: &'a [(&'static str, &'static str)],
rows: &'a [Row],
}
impl TableDelegate for Tones<'_> {
fn row_count(&self) -> usize {
self.rows.len()
}
fn row_key(&self, row: usize) -> u64 {
self.rows[row].key(row)
}
fn cell(&mut self, ui: &mut egui::Ui, cell: &TableCell<'_>) {
// A caption's cells stay empty: it reads across the row.
let Row::Tone(tone) = self.rows[cell.row] else {
return;
};
let (name, amp) = self.names[tone];
match cell.key {
"number" => cell.label(ui, (tone + 1).to_string()),
"name" => cell.label(ui, name),
_ => cell.label(ui, amp),
};
}
fn is_current(&self, row: usize) -> bool {
self.playing == Some(self.row_key(row))
}
fn is_selected(&self, row: usize) -> bool {
self.selected.contains(self.row_key(row))
}
fn row_overlay(&mut self, row: &TableRowOverlay<'_>) {
if let Row::Group(name, count) = self.rows[row.row] {
let painter = row.painter();
painter.text(
egui::pos2(row.rect.left() + 12.0, row.rect.center().y),
egui::Align2::LEFT_CENTER,
format!("{} {count}", name.to_uppercase()),
egui::FontId::proportional(11.0),
tokens(painter.ctx()).muted_foreground,
);
}
}
}
ui.vertical(|ui| {
ui.set_width(420.0);
ui.label(
"Double-click a tone to play it. Shift and Ctrl or Cmd select several, \
kept by the app. Right-click a header to choose the columns.",
);
if ui
.add(Button::new("Show the tone playing").small())
.clicked()
{
state.reveal_playing = true;
}
let mut columns = vec![
Column::new("number", "#")
.width(36.0)
.fixed()
.resizable(false),
Column::new("name", "Name").width(180.0).fill().sortable(),
];
if state.amp_shown {
columns.push(Column::new("amp", "Amp").width(160.0).sortable());
}
let names = [
("Clean Chime", "Twin Reverb"),
("Edge of Breakup", "Deluxe"),
("Plexi Crunch", "1959 Super Lead"),
("Brown Sound", "5150"),
("Fuzz Wall", "Big Muff"),
("Glass Pad", "AC30"),
("Low Growl", "SVT"),
("Surf Drip", "Showman"),
("Dime Stack", "Recto"),
("Velvet Lead", "Dumble"),
("Spring Air", "Princeton"),
("Tight Rhythm", "JCM800"),
];
// Two groups, each sorted under its caption.
let mut rows = Vec::new();
for (group, tones) in [("Setlists", 0..2), ("Library", 2..names.len())] {
let mut order: Vec<usize> = tones.collect();
if let Some(sort) = &state.tones_table.sort {
sort_rows(&mut order, sort.sort, |tone| {
let (name, amp) = names[tone];
SortKey::text(if sort.column == "amp" { amp } else { name })
});
}
rows.push(Row::Group(group, order.len()));
rows.extend(order.into_iter().map(Row::Tone));
}
let mut tones = Tones {
playing: state.playing,
selected: &state.tones_selected,
names: &names,
rows: &rows,
};
// The look would set it for every table: `.replace(table_styles::Standard, Amp)`.
// The story keeps the selection, and the bars show at rest.
let mut table = Table::new(&mut state.tones_table, &columns)
.id_salt("tones")
.style(&Amp)
.max_height(300.0)
.multi_select(true)
.app_selection(true)
.scrollbar_mode(ScrollbarMode::Always)
// Always sorted, as TonePush is: a click turns the sort
// round.
.sort_cycle(SortCycle::AscendingDescending)
// The rows stop short of the bar, as egui's thin bars keep
// the content clear.
.scrollbar_inset(4.0);
// The tone playing with two rows above it, at the top.
if std::mem::take(&mut state.reveal_playing)
&& let Some(row) = (0..rows.len()).find(|&row| tones.is_current(row))
{
table = table.scroll_to_rows(row.saturating_sub(2)..=row, Some(egui::Align::Min));
}
let shown = table.show(ui, &mut tones);
if let Some((row, pick)) = shown.picked {
let selected = &mut state.tones_selected;
selected.pick(row, pick, rows.len(), |row| rows[row].key(row));
// A caption is not a tone: a range across one leaves it out.
let tones_only: Vec<u64> = selected
.keys()
.filter(|&key| key < names.len() as u64)
.collect();
if tones_only.len() < selected.len() {
selected.set(tones_only);
}
}
if let Some(row) = shown.activated
&& let Row::Tone(tone) = rows[row]
{
state.playing = Some(tone as u64);
}
// The column chooser: a menu at the pointer, on a right-click
// on any header.
let chooser = ui.scope_id().with("tone columns");
if shown.header_secondary_clicked.is_some()
&& let Some(at) = ui.input(|input| input.pointer.interact_pos())
{
Menu::open_at(ui.ctx(), chooser, at);
}
Menu::new()
.id(chooser)
.show_context(&shown.response, |menu| {
menu.label("Columns");
if menu
.add(MenuItem::new("Amp").checked(state.amp_shown))
.clicked()
{
state.amp_shown = !state.amp_shown;
}
});
});
Views of a crate
/// Solco's library, as a table style: the primary row filled, with
/// an accent edge, and the other selected rows in a softer fill,
/// whether or not the table has the focus.
struct Deck;
impl TableStyle for Deck {
fn paint_row(&self, row: &TableRowConfiguration<'_>) {
let theme = row.theme;
let fill = if row.state.primary {
theme.table.active
} else if row.state.selected {
theme.table.active.gamma_multiply(0.45)
} else if row.state.hovered {
theme.table.hover
} else {
egui::Color32::TRANSPARENT
};
row.paint_fill(fill);
// The track's colour, fainter on a selected row.
if let Some(tint) = row.state.tint {
let tint = if row.state.selected {
tint.gamma_multiply(0.35)
} else {
tint
};
row.painter().rect_filled(row.rect, 0.0, tint);
}
row.paint_divider(theme.table.row_border);
if row.state.primary && !row.fixed {
let edge = egui::Rect::from_min_size(
row.row_rect.min,
egui::vec2(3.0, row.row_rect.height()),
);
row.painter()
.rect_filled(edge, 0.0, theme.primary.background);
}
}
fn paint_header(&self, header: &TableHeaderConfiguration<'_>) {
header.paint_title(None);
}
}
ui.vertical(|ui| {
ui.set_width(420.0);
ui.label(
"The title takes the room the others leave; drag an edge to keep a width, \
double-click it to fit the column to its content. Shift and Ctrl or Cmd \
select several; the one picked last stays marked as the primary row.",
);
ui.add(Toggle::new(&mut state.compact, "Compact"));
let columns = [
Column::new("title", "Title").width(160.0).min_width(120.0),
Column::new("artist", "Artist").width(120.0),
Column::new("bpm", "BPM").width(60.0).text_right(),
];
// A tall row with the artist under the title, or one line.
let (height, padding) = if state.compact {
(24.0, egui::vec2(8.0, 2.0))
} else {
(46.0, egui::vec2(10.0, 6.0))
};
let mut tracks = Crate {
tracks: &state.tracks[..40],
compact: state.compact,
};
Table::new(&mut state.crates_table, &columns)
.id_salt("crate")
.style(&Deck)
.multi_select(true)
.row_height(height)
.cell_padding(padding)
.max_height(260.0)
.show(ui, &mut tracks);
});
Small, unbordered
ui.vertical(|ui| {
ui.set_width(420.0);
let columns = [
Column::new("planet", "Planet").width(160.0),
Column::new("moons", "Moons").width(100.0).text_right(),
Column::new("ring", "Rings").width(100.0).text_center(true),
];
let planets = [
("Mercury", 0, "No"),
("Venus", 0, "No"),
("Earth", 1, "No"),
("Mars", 2, "No"),
("Jupiter", 95, "Yes"),
("Saturn", 146, "Yes"),
];
Table::new(&mut state.small, &columns)
.id_salt("planets")
.size(Size::Small)
.bordered(false)
.stripe(true)
.show_cells(ui, planets.len(), |ui, cell| {
let (name, moons, rings) = planets[cell.row];
match cell.column {
0 => cell.label(ui, name),
1 => cell.label(ui, moons.to_string()),
_ => cell.label(ui, rings),
};
});
});
Wider than its room
ui.vertical(|ui| {
ui.set_width(420.0);
ui.label(
"A fixed column, columns that scroll sideways and rows that fit: the table grows by its rows' inset, so the last row shows whole above the bar, and the fixed column runs to the bottom.",
);
let columns = [
Column::new("planet", "Planet").width(110.0).fixed(),
Column::new("moons", "Moons").width(100.0).text_right(),
Column::new("day", "Day").width(120.0).text_right(),
Column::new("year", "Year").width(120.0).text_right(),
Column::new("ring", "Rings").width(100.0).text_center(true),
];
let planets = [
("Mercury", 0, "58.6 days", "88 days", "No"),
("Venus", 0, "243 days", "225 days", "No"),
("Earth", 1, "24 hours", "365 days", "No"),
("Mars", 2, "24.6 hours", "687 days", "No"),
];
Table::new(&mut state.wide, &columns)
.id_salt("wide planets")
.scrollbar_mode(ScrollbarMode::Always)
.scrollbar_inset(4.0)
.show_cells(ui, planets.len(), |ui, cell| {
let (name, moons, day, year, rings) = planets[cell.row];
match cell.column {
0 => cell.label(ui, name),
1 => cell.label(ui, moons.to_string()),
2 => cell.label(ui, day),
3 => cell.label(ui, year),
_ => cell.label(ui, rings),
};
});
});
With a toolbar on top
ui.vertical(|ui| {
ui.set_width(420.0);
// Nothing between them: the toolbar is the table's top.
ui.spacing_mut().item_spacing.y = 0.0;
Toolbar::new().attached().show(ui, |bar| {
bar.add(
fastframe_ui::Input::search(&mut state.filter)
.placeholder("Filter planets")
.small()
.width(180.0),
);
bar.right(|bar| bar.button(Button::primary("Add planet")));
});
let columns = [
Column::new("planet", "Planet").width(200.0).fill(),
Column::new("moons", "Moons").width(100.0).text_right(),
];
let query = state.filter.to_lowercase();
let planets: Vec<(&str, u32)> = [
("Mercury", 0),
("Venus", 0),
("Earth", 1),
("Mars", 2),
("Jupiter", 95),
("Saturn", 146),
]
.into_iter()
.filter(|(name, _)| name.to_lowercase().contains(&query))
.collect();
/// The planets the filter keeps, and a line when it keeps none.
struct Planets<'a>(&'a [(&'static str, u32)]);
impl TableDelegate for Planets<'_> {
fn row_count(&self) -> usize {
self.0.len()
}
fn cell(&mut self, ui: &mut egui::Ui, cell: &TableCell<'_>) {
let (name, moons) = self.0[cell.row];
match cell.column {
0 => cell.label(ui, name),
_ => cell.label(ui, moons.to_string()),
};
}
fn empty_state(&mut self, ui: &mut egui::Ui) -> bool {
ui.add_space(40.0);
ui.label("No planet matches the filter.");
true
}
}
Table::new(&mut state.filtered, &columns)
.id_salt("filtered planets")
.attached_top(true)
.show(ui, &mut Planets(&planets));
});
Loading
ui.vertical(|ui| {
ui.set_width(420.0);
ui.add(Toggle::new(&mut state.loading, "Loading"));
let columns = [
Column::new("name", "Name").width(200.0),
Column::new("size", "Size").width(100.0).text_right(),
];
Table::new(&mut state.loading_table, &columns)
.id_salt("loading")
.loading(state.loading)
.show_cells(ui, 3, |ui, cell| {
cell.label(ui, format!("Row {} col {}", cell.row + 1, cell.column + 1));
});
});
The story above is gallery/src/stories/table.rs, running in your browser. Every snippet on this page is cut from it.