Skip to main content

Table

Struct Table 

Source
pub struct Table<T, S, M> { /* private fields */ }
Expand description

A scrollable table of value-keyed rows, declared with component.

A table is a List with columns. Rows are ListItems in display order, each identified by a value you choose, and the app owns the cursor, the selection, the column cursor, the sort order, and — if it wants them — both scroll offsets. Supply one width per column. The default row shows the item’s label in the first column; paint_item fills every column, and is called only for the rows on screen.

§Cursor and selection are different things

The cursor is where the user is looking: arrow keys, Home, End, the page keys and the pointer move it, and moving it commits nothing. Selection is the choice: Enter, Space, or a left click commits a row. The cursor is a TableCursor — on a row, or on the header above the first row.

§Bindings

Each binding is a pair — a reader for the current value and a constructor for the message that changes it — passed in one call so the two cannot drift apart. Rows are keyed by item value, never by position, so sorting or filtering keeps the same record current. Columns are keyed by index into the declared widths: if you hide or reorder columns, remap the stored column, the sort column and the sortable indices to match.

Item values must be unique within each declaration, or the cursor, selection and pointer actions are ambiguous. A debug build panics on duplicates during declaration.

  • item_focus — the cursor and the top-row offset. Its message carries the new TableCursor and the offset that keeps it in view; store both in one update when scroll is bound.
  • selection or multi_selection — single choice or any number of toggled rows (mutually exclusive). Store or toggle the value, and set the cursor to TableCursor::Row of the same value in that update, so keys continue from a clicked row.
  • column_focus — the column cursor and the horizontal column offset; store both in one update when horizontal_scroll is bound.
  • sort — the requested TableSort. Reorder the records and store the request; move the column cursor to the sorted column too if you like.
  • scroll and horizontal_scroll — the vertical and horizontal offsets, for when something outside the table has to know or drive them. Unbound, the table scrolls itself.

Disabled items are dimmed and skipped by both keyboard and mouse.

§The header

With item_focus bound and at least one sortable heading, the header is a place the cursor can go: Up from the first enabled row — or any vertical step in a table with no enabled row — emits TableCursor::Header. On the header the cursor is on one heading: the column cursor when column_focus is bound, otherwise the sorted column, otherwise the first sortable heading. Left and Right move it among the columns that have headings, and only when column_focus is bound. Enter or Space sorts its column, and Down and the other forward keys come back into the rows. Without a sortable heading the header is not a place, and Up at the top stays put, as on a list. Clicking a sortable heading sorts by it either way, and a key set with sort_key sorts the cursor’s column from the rows too.

§Pointer

Pointer motion over a row moves the row cursor there. With column_focus bound, motion over another wholly visible cell of the cursor row moves the column cursor to it without scrolling. A click commits the row through selection, or sorts a sortable heading. Hovering a heading only highlights it.

§Focus

A table is a Tab stop when it is enabled, has at least one column, and a key can act there: column_focus is bound, the header is a place, a sort_key is set and a heading sorts, or item_focus is bound and some row is enabled. Tab and Shift+Tab stay ordinary component traversal.

§Wide tables

Columns that fit are laid out exactly as Ratatui lays them out. They scroll horizontally, keeping the active column in view, only when their rigid widths and the spacing exceed the inner width: Length and Min widths, and for a Fill column the wider of its heading (plus room for a sort mark when it sorts) and its footer cell, at least 1. Percentage and Ratio columns take their share of what is left after spacing, and Max columns can shrink to nothing. Once scrolling, every column takes that width — a Max column its maximum, a Percentage or Ratio column its share — and flex is ignored, so prefer Length or Min widths for a table that can scroll. See frozen_columns to pin leading columns.

use ratatui::{layout::Constraint, widgets::Row};
use ratcn::{ListItem, Table, TableCursor, TableSort};

let _table = Table::new(
    [ListItem::new(1u64, "Groceries"), ListItem::new(2, "Rent")],
    [Constraint::Fill(1), Constraint::Length(10)],
)
.header(["Description", "Amount"])
.paint_item(|_: &AppState, row| Row::new([row.label.to_owned(), "$42.00".to_owned()]))
.item_focus(|s| s.cursor, |cursor, _| Msg::Cursor(cursor))
.selection(|s| s.selected, Msg::Select)
.column_focus(|s| Some(s.column), |column, _| Msg::Column(column))
.sort([0, 1], |s| s.sort, Msg::Sort);

Implementations§

Source§

impl<T, S, M> Table<T, S, M>

Source

pub fn new( items: impl IntoIterator<Item = impl Into<ListItem<T>>>, widths: impl IntoIterator<Item = impl Into<Constraint>>, ) -> Self

Build a table over items identified by unique values, in display order.

Source

pub fn from_shared( items: Arc<[ListItem<T>]>, widths: impl IntoIterator<Item = impl Into<Constraint>>, ) -> Self

Reuse app-held items across frame declarations.

Source

pub fn header( self, headings: impl IntoIterator<Item = impl Into<Line<'static>>>, ) -> Self

Fixed one-line header, one heading per column. A heading keeps its own spans, style and alignment; a sorted one gains a ▲/▼ mark on the side away from its alignment, when the column has room for it.

Source

pub fn footer( self, cells: impl IntoIterator<Item = impl Into<Line<'static>>>, ) -> Self

Fixed one-line footer, outside the scrollable body.

Source

pub fn block(self, block: Block<'static>) -> Self

Surround the table with a native block (including titles and padding).

Source

pub const fn column_spacing(self, spacing: u16) -> Self

Space between columns, one cell by default.

Source

pub const fn flex(self, flex: Flex) -> Self

Position columns using Ratatui’s layout policy. Ignored while the columns overflow and scroll horizontally.

Source

pub const fn row_height(self, height: u16) -> Self

Uniform body-row height for paging and hit-testing. Row-local heights and margins are replaced; use TableWidget for variable-height rows. A height of 0 is treated as 1.

Source

pub fn paint_item( self, paint: impl Fn(&S, ListItemState<'_, T>) -> Row<'static> + 'static, ) -> Self

Format a visible item with native cells, spans, alignment and styling.

The closure gets app state and a ListItemState describing the row, and returns one cell per column; cells past the declared widths are dropped. The resolved row style is painted beneath the returned row, so unstyled text inherits the row’s state colors while an explicit foreground or modifier on the Row, a Cell or a Span wins — except on the selected cursor row (or its cursor cell, with a column cursor), which is lettered in selected_focused_foreground so it stays legible on the primary fill. A background set there replaces the row’s fill — cursor row and band included — so check !row.focused when adding custom row backgrounds such as zebra striping. Every row is forced to row_height with zero margins.

Source

pub fn item_focus( self, read: impl Fn(&S) -> Option<TableCursor<T>> + 'static, on_change: impl Fn(TableCursor<T>, usize) -> M + 'static, ) -> Self

Bind the cursor: where to read it from, and what message moves it.

read returns where the cursor is, or None when it is nowhere yet — the first vertical navigation key then moves it onto the first enabled row. A TableCursor::Row whose value no row carries is treated the same way, as is TableCursor::Header while the header cannot take the cursor. on_change is called with the new cursor and the resulting top-row offset. Store both in one update when scroll is bound; an unbound table can ignore the offset.

The cursor reaches TableCursor::Header only while the header has a sortable heading; see the header. Moving the cursor commits nothing; see selection. Without this binding rows remain available for painting, bound scrolling and pointer selection, and take no vertical keys; column_focus and sort_key still take theirs.

Source

pub fn selection( self, read: impl Fn(&S) -> Option<T> + 'static, on_select: impl Fn(T) -> M + 'static, ) -> Self

Bind single selection: at most one row chosen at a time.

read returns the selected value, or None for nothing selected. on_select is called with the row the user committed — Enter or Space on the cursor row, or a left click on a row. A click need not be preceded by pointer motion, so when item_focus is bound, the update handling this message should also set the cursor to TableCursor::Row of the same value.

§Panics

Rendering panics if this is combined with multi_selection: a table is one mode or the other, and Enter commits through whichever one is bound.

Source

pub fn multi_selection( self, read: impl Fn(&S, &T) -> bool + 'static, on_toggle: impl Fn(T) -> M + 'static, ) -> Self

Bind multi-selection: any number of rows chosen at once.

read is a predicate asked “is this row selected?” for each visible row, so your app can store the selection in a HashSet, a flag on each record, or a computed rule without converting it every frame. on_toggle is called with the row the user flipped via Enter, Space, or a left click; your update function decides whether to add or remove it. When item_focus is also bound, the update handling a click should set the cursor to TableCursor::Row of the same value.

§Panics

Rendering panics if this is combined with selection.

Source

pub fn column_focus( self, read: impl Fn(&S) -> Option<usize> + 'static, on_change: impl Fn(usize, usize) -> M + 'static, ) -> Self

Bind the column cursor for Left/Right (or h/l) and cell highlighting.

read returns the active column’s index into the declared widths, or None for none yet. on_change is called with the new column and the resulting horizontal column offset — the number of non-frozen columns scrolled off to the left once the view has moved as little as it must to show that column. Store both in one update when horizontal_scroll is bound; an unbound table can ignore the offset. Adjustments the table makes while rendering, such as keeping the column in view after a sort handler moved it or after a resize, cannot emit a message.

Binding this makes the table a Tab stop even without item_focus. Pointer motion over another wholly visible cell of the cursor row moves the column there, as described under pointer; headings do not. To move the column when a heading is clicked, do it in sort’s update.

Source

pub fn sort( self, columns: impl IntoIterator<Item = usize>, read: impl Fn(&S) -> Option<TableSort> + 'static, on_change: impl Fn(TableSort) -> M + 'static, ) -> Self

Enable sorting on the specified zero-based header columns. Clicking a sortable heading, or Enter or Space on it while the cursor is on the header, requests ascending order, or descending when that column is already sorted ascending.

read returns the current sort, if any. on_change is called with the requested TableSort: reorder the records, store the request, and move the column cursor to its column too if you like. Only columns with a heading sort.

Source

pub fn sort_key(self, key: impl Into<KeyChord>) -> Self

A key that sorts the cursor’s column from anywhere in the table, rows or header, without moving the row cursor. None by default.

The column is the column cursor when column_focus reads one, otherwise the sorted column, otherwise the first sortable heading; the request toggles exactly as a click does. When that column does not sort, or sort is unbound, the key bubbles to the app. It takes precedence over the table’s own keys: pick one that does not collide with h/j/k/l if you want those.

Accepts anything that converts into a KeyChord, so a bare char or KeyCode works, with ctrl / alt for combinations. Like every KeyChord, matching ignores Shift. For example:

use ratatui::layout::Constraint;
use ratcn::{ListItem, Table, TableSort, runtime::KeyChord};

let _table: Table<u64, AppState, Msg> =
    Table::new([ListItem::new(1u64, "Rent")], [Constraint::Fill(1)])
        .header(["Description"])
        .sort([0], |s: &AppState| s.sort, Msg::Sort)
        .sort_key(KeyChord::from('s').ctrl());
Source

pub const fn frozen_columns(self, count: usize) -> Self

Pin the first count columns on the left while remaining columns scroll horizontally. Defaults to 0.

Horizontal scrolling activates automatically whenever the columns cannot fit the table’s inner width (see wide tables); when everything fits, frozen_columns has no visual effect. Frozen columns should fit the view with room to spare: freezing every column, or columns wider than the view, leaves nothing to scroll. Once columns scroll behind the frozen ones, a thin │ rule appears in the spacing gap beside them — only when column_spacing is above 0, since without a gap there is nowhere to draw it.

Source

pub fn scroll( self, read: impl Fn(&S) -> usize + 'static, on_change: impl Fn(usize) -> M + 'static, ) -> Self

Bind the requested vertical scroll offset — the index of the topmost visible row.

Before paint, the table adjusts the requested value to keep the cursor row visible. Cursor movement computes the resulting offset from the view on screen, counting wheel notches not yet painted, and passes it to item_focus’s on_change, so its update can store cursor and offset together. The vertical wheel scrolls the view without moving the cursor, emits the offset one notch away, and bubbles at either end. Render-driven adjustment cannot emit a message.

Left unbound, the table owns the offset itself and keys and the wheel still scroll it.

Source

pub fn horizontal_scroll( self, read: impl Fn(&S) -> usize + 'static, on_change: impl Fn(usize) -> M + 'static, ) -> Self

Bind the requested horizontal column offset — the number of non-frozen columns scrolled off to the left.

Before paint, the table adjusts the requested value to keep the active column visible. Column movement computes the same resulting offset and passes it to column_focus’s on_change, so its update can store column and offset together. The horizontal wheel scrolls the view without moving the column, emits the offset one notch away, and bubbles at either end. Render-driven adjustment, such as after a resize or a sort handler moving the column, cannot emit a message.

Left unbound, the table owns the offset itself and column movement and the wheel still scroll it.

Source

pub fn style(self, style: impl Fn(&Theme) -> TableStyle + 'static) -> Self

Resolve custom colors against the current theme each frame.

Source

pub const fn disabled(self, disabled: bool) -> Self

Dim the control and remove it from input and focus traversal.

Trait Implementations§

Source§

impl<T: Clone + PartialEq + 'static, S, M> Component<S, M> for Table<T, S, M>

Source§

fn declare(&mut self, ctx: &mut DeclareCtx<'_, S, M>)

Declare the component: lay out its area, declare its descendants, and record whatever handle_event will need to read back. Read more
Source§

fn paint(&mut self, ctx: &mut PaintCtx<'_, S>)

Paint the component. ctx carries the paint surface, area, app state, theme, and interaction state. Read more
Source§

fn handle_event( &mut self, event: &Event, state: &S, ctx: &mut EventCtx<'_>, ) -> EventResult<M>

Offer this component an event. Read more
Source§

fn scope_options(&self, _: &S) -> ScopeOptions

The scope this component opens around its descendants. Read once, before declare, so it cannot depend on paint; state is the app state this component is being declared with.
Source§

fn interaction_area(&self, area: Rect, _state: &State) -> Rect

Return the area used for focus, hit-testing, and event routing. Read more
Source§

fn reveal_in_viewport( &mut self, _target: Rect, _state: &State, _ctx: &mut EventCtx<'_>, ) -> bool

Bring target into view inside this component’s viewport. Read more
Source§

impl<T, S, M> Debug for Table<T, S, M>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T, S, M> !RefUnwindSafe for Table<T, S, M>

§

impl<T, S, M> !Send for Table<T, S, M>

§

impl<T, S, M> !Sync for Table<T, S, M>

§

impl<T, S, M> !UnwindSafe for Table<T, S, M>

§

impl<T, S, M> Forget for Table<T, S, M>

§

impl<T, S, M> Freeze for Table<T, S, M>
where *const ArcInner<[ListItem<T>]> is !null: Freeze, PhantomData<ArcInner<[ListItem<T>]>>: Freeze, *const u8 is !null: Freeze, PhantomData<Constraint>: Freeze, PhantomData<Line<'static>>: Freeze, PhantomData<(Option<TitlePosition>, Line<'static>)>: Freeze, InternalBitFlags: Freeze, InternalBitFlags: Freeze, &'static str: Freeze, *const ArcInner<dyn CellEffect> is !null: Freeze, PhantomData<ArcInner<dyn CellEffect>>: Freeze, *const dyn Fn(&S) -> Option<TableCursor<T>> is !null: Freeze, PhantomData<dyn Fn(&S) -> Option<TableCursor<T>>>: Freeze, *const dyn Fn(TableCursor<T>, usize) -> M is !null: Freeze, PhantomData<dyn Fn(TableCursor<T>, usize) -> M>: Freeze, *const dyn Fn(&S) -> Option<T> is !null: Freeze, PhantomData<dyn Fn(&S) -> Option<T>>: Freeze, *const dyn Fn(T) -> M is !null: Freeze, PhantomData<dyn Fn(T) -> M>: Freeze, *const dyn Fn(&S, &T) -> bool is !null: Freeze, PhantomData<dyn Fn(&S, &T) -> bool>: Freeze, *const dyn Fn(&S) -> Option<usize> is !null: Freeze, PhantomData<dyn Fn(&S) -> Option<usize>>: Freeze, *const dyn Fn(usize, usize) -> M is !null: Freeze, PhantomData<dyn Fn(usize, usize) -> M>: Freeze, *const dyn Fn(&S) -> Option<TableSort> is !null: Freeze, PhantomData<dyn Fn(&S) -> Option<TableSort>>: Freeze, *const dyn Fn(TableSort) -> M is !null: Freeze, PhantomData<dyn Fn(TableSort) -> M>: Freeze, PhantomData<usize>: Freeze, *const dyn Fn(&S) -> usize is !null: Freeze, PhantomData<dyn Fn(&S) -> usize>: Freeze, *const dyn Fn(usize) -> M is !null: Freeze, PhantomData<dyn Fn(usize) -> M>: Freeze, *const dyn Fn(&S, ListItemState<'_, T>) -> Row<'static> is !null: Freeze, PhantomData<dyn Fn(&S, ListItemState<'_, T>) -> Row<'static>>: Freeze, *const dyn Fn(&Theme) -> TableStyle is !null: Freeze, PhantomData<dyn Fn(&Theme) -> TableStyle>: Freeze, PhantomData<u16>: Freeze, *const RcInner<[Rect]> is !null: Freeze, PhantomData<RcInner<[Rect]>>: Freeze,

§

impl<T, S, M> Move for Table<T, S, M>

§

impl<T, S, M> Unpin for Table<T, S, M>
where Arc<[ListItem<T>]>: Unpin, *const u8 is !null: Unpin, InternalBitFlags: Unpin, &'static str: Unpin, String: Unpin, InternalBitFlags: Unpin, Arc<dyn CellEffect>: Unpin, Box<dyn Fn(&S) -> Option<TableCursor<T>>>: Unpin, Box<dyn Fn(TableCursor<T>, usize) -> M>: Unpin, Box<dyn Fn(&S) -> Option<T>>: Unpin, Box<dyn Fn(T) -> M>: Unpin, Box<dyn Fn(&S, &T) -> bool>: Unpin, Box<dyn Fn(&S) -> Option<usize>>: Unpin, Box<dyn Fn(usize, usize) -> M>: Unpin, Box<dyn Fn(&S) -> Option<TableSort>>: Unpin, Box<dyn Fn(TableSort) -> M>: Unpin, Box<dyn Fn(&S) -> usize>: Unpin, Box<dyn Fn(usize) -> M>: Unpin, Box<dyn Fn(&S, ListItemState<'_, T>) -> Row<'static>>: Unpin, Box<dyn Fn(&Theme) -> TableStyle>: Unpin, Rc<[Rect]>: Unpin,

§

impl<T, S, M> UnsafeUnpin for Table<T, S, M>
where *const ArcInner<[ListItem<T>]> is !null: UnsafeUnpin, PhantomData<ArcInner<[ListItem<T>]>>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<Constraint>: UnsafeUnpin, PhantomData<Line<'static>>: UnsafeUnpin, PhantomData<(Option<TitlePosition>, Line<'static>)>: UnsafeUnpin, InternalBitFlags: UnsafeUnpin, InternalBitFlags: UnsafeUnpin, &'static str: UnsafeUnpin, *const ArcInner<dyn CellEffect> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn CellEffect>>: UnsafeUnpin, *const dyn Fn(&S) -> Option<TableCursor<T>> is !null: UnsafeUnpin, PhantomData<dyn Fn(&S) -> Option<TableCursor<T>>>: UnsafeUnpin, *const dyn Fn(TableCursor<T>, usize) -> M is !null: UnsafeUnpin, PhantomData<dyn Fn(TableCursor<T>, usize) -> M>: UnsafeUnpin, *const dyn Fn(&S) -> Option<T> is !null: UnsafeUnpin, PhantomData<dyn Fn(&S) -> Option<T>>: UnsafeUnpin, *const dyn Fn(T) -> M is !null: UnsafeUnpin, PhantomData<dyn Fn(T) -> M>: UnsafeUnpin, *const dyn Fn(&S, &T) -> bool is !null: UnsafeUnpin, PhantomData<dyn Fn(&S, &T) -> bool>: UnsafeUnpin, *const dyn Fn(&S) -> Option<usize> is !null: UnsafeUnpin, PhantomData<dyn Fn(&S) -> Option<usize>>: UnsafeUnpin, *const dyn Fn(usize, usize) -> M is !null: UnsafeUnpin, PhantomData<dyn Fn(usize, usize) -> M>: UnsafeUnpin, *const dyn Fn(&S) -> Option<TableSort> is !null: UnsafeUnpin, PhantomData<dyn Fn(&S) -> Option<TableSort>>: UnsafeUnpin, *const dyn Fn(TableSort) -> M is !null: UnsafeUnpin, PhantomData<dyn Fn(TableSort) -> M>: UnsafeUnpin, PhantomData<usize>: UnsafeUnpin, *const dyn Fn(&S) -> usize is !null: UnsafeUnpin, PhantomData<dyn Fn(&S) -> usize>: UnsafeUnpin, *const dyn Fn(usize) -> M is !null: UnsafeUnpin, PhantomData<dyn Fn(usize) -> M>: UnsafeUnpin, *const dyn Fn(&S, ListItemState<'_, T>) -> Row<'static> is !null: UnsafeUnpin, PhantomData<dyn Fn(&S, ListItemState<'_, T>) -> Row<'static>>: UnsafeUnpin, *const dyn Fn(&Theme) -> TableStyle is !null: UnsafeUnpin, PhantomData<dyn Fn(&Theme) -> TableStyle>: UnsafeUnpin, PhantomData<u16>: UnsafeUnpin, *const RcInner<[Rect]> is !null: UnsafeUnpin, PhantomData<RcInner<[Rect]>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.