Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Tables

A resource’s Table, set with ResourceDef::table, declares its list page: the columns, and the search, sort, filter, grouping and pagination the list offers. It depends on no request: the panel builds it once when it mounts and serves that table to every request. The same declaration drives the CSV export.

The table defaults to the model’s, User::table(), which #[derive(tablo::PanelModel)] writes: a sortable column per field, whether a form or Toasty writes it, so a #[default] created_at is listed too, and #[columns(skip)] leaves out a field such as a password hash. Extend the model’s table, whose filters(..) add to the ones a field’s #[columns(filter)] declares, or declare the columns yourself:

#![allow(unused)]
fn main() {
ResourceDef::new().table(User::table().filters(TernaryFilter::new(lens!(User.active))))
}
#![allow(unused)]
fn main() {
impl Resource for UserResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            .table({
                // Each field as the default table shows it: a searchable, sortable text, a
                // sortable number and a yes or no.
                let col = User::columns();
                Table::new((col.name, col.email, col.age, col.active)).page_size(20)
            })
    }
}
}

Each row is keyed by its record’s primary key, so a model with a composite key lists without row actions or bulk selection.

A model’s columns

The derive also writes User::columns(), the read-side twin of a record form’s controls(): one FieldColumn per field the default table or detail page shows, named like the field. Placed as it is, col.name is the column the default table lists, with the field’s #[columns(..)] keys; in a detail page’s tuple it is the default detail page’s, which keeps a timestamp’s time where the table shows its day. A kind method turns it into a column type’s own builder over the same field, to reshape as any column: col.name.text().limit(24), col.created_at.date(), col.featured.toggle(). The kinds are text, date, boolean, list, icon, color, image, file, rich_text, embedded, repeater, and the editable text_input, select and toggle; each compiles only for a field its column reads, so a toggle over a String is a compile error. col.status.lens() hands the field’s lens to a filter or a tab.

columns() leaves out what the default table does: a key Toasty generates, a foreign key, the tenant column, a relation and a #[columns(skip)] field. Name one of those with lens!.

Lenses

lens!(User.name) is the low-level tool columns() is built on. It names a field once and yields both halves a column needs: the path a query sorts and searches on (User::fields().name()) and the reader that renders the loaded value (&user.name). The two cannot disagree. A lens names a field of the model or, through an embedded value, its leaf (lens!(Post.seo.title)), which binds the flattened seo_title column; a lens through a relation does not compile, since a relation’s records are not part of the row. relation!(Post.author) is a relation’s lens: the include that loads it and the reader of the loaded records, which the relation columns take. Builders that only query, such as the filters, Tenancy::column and the Field constructors, take either a lens or a plain path; this guide names a field with lens! wherever one fits, and writes User::fields() only where a lens cannot go: a query expression, a path through a relation such as Tenancy::via’s, and the foreign key Relation::has_many takes.

Columns

The built-in columns cover the common cells: TextColumn for any value, DateColumn for a calendar day, BooleanColumn, FileColumn and ImageColumn for uploads, RichTextColumn, ColorColumn, EmbeddedColumn for an embedded value, ListColumn for a list column such as a multiple choice’s, a badge per value, ComputedColumn for what your closure returns, and RelationColumn and CountColumn for related records. Each type’s page in the API docs says what its cell shows, what the export writes, and whether it searches and sorts.

#![allow(unused)]
fn main() {
pub fn date_column() -> DateColumn<User, jiff::Timestamp> {
    User::columns().created_at.date().sortable()
}
}
  • Labels. A field or relation column is labelled from its field name (created_at → “Created at”), or .label(..).
  • Detail pages. The same columns build a resource’s detail page.
  • Closures. Every closure a column, row_color or a RowLink takes gets the request’s Cx first, then the row or the value, as a policy does: |cx, order: &Order| .. reads the reader’s locale or user, and |_, order: &Order| .. reads the row alone.
  • Relations. A relation column declares the include its relation! names, so the list, the export and the detail page load the related records with the page’s rows. A relation no column includes is not loaded; a ComputedColumn whose closure reads one, say to combine two, declares each with .include_unscoped(..), and reads it under no resource’s query or policy.
#![allow(unused)]
fn main() {
pub fn author_column() -> RelationColumn<Post> {
    RelationColumn::new::<AuthorResource>(
        relation!(Post.author),
        lens!(Author.name),
        |_, a: &Author| a.name.clone(),
    )
}

pub fn comment_count_column() -> CountColumn<Post> {
    CountColumn::of::<CommentResource>(relation!(Post.comments))
}
}

A relation column over R shows only the related records R shows the user, as a relationship choice over R offers them, so a list never leaks another tenant’s author or a comment the user cannot view (RelationColumn). A CountColumn counts in the database, one count query per row, and loads none of the records it counts.

  • Widths. The table lays out automatically, a column as wide as its content; .width(..) takes a ColumnWidth to wrap a long value or fix a width.
  • Rows. A row opens its record’s view page, or its edit page when it has no view page, wherever it is clicked; the checkbox and the action buttons keep their own click.
  • Row actions. A row’s actions sit side by side at its end; .action_layout(ActionLayout::Menu) puts them behind one button instead. .row_link(..) adds a RowLink among them, a plain link such as a product’s storefront page, which posts nothing and checks no policy.

A misdeclared table, such as two columns with the same name, fails the mount, and rendering it on your own page fails with the same errors.

Presenting values

A TextColumn presents its value beyond plain text:

.badge() renders the value as a badge, .color(..) colors it, .description(..) adds a muted second line, .numeric(decimals) and .money(currency) format a number, .weight(..) sets how heavy its text renders, and .align(..) moves it to the end; TextColumn has each method’s rules.

An Options enum gives each variant its badge color with #[option(color = "…")], one of gray, primary, success, warning, danger and info. Each paints with a theme token, so a theme recolors every badge at once:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Copy, PartialEq, Eq, toasty::Embed, tablo::Options)]
pub enum PostStatus {
    #[option(color = "gray")]
    Draft,
    #[option(color = "success")]
    Published,
}
}
#![allow(unused)]
fn main() {
pub fn user_columns() -> Table<User> {
    let col = User::columns();
    Table::new((
        // The email as a muted line under the name.
        col.name
            .text()
            .description(|_, user: &User| user.email.clone()),
        // `12,345`, right-aligned.
        col.age.text().numeric(0),
        // `$1,234.50`, from a field holding cents.
        ComputedColumn::new("Balance", |_, user: &User| {
            Currency::USD.minor_units().format(user.age * 1250)
        })
        .align(Alignment::End),
    ))
}

pub fn status_badge() -> TextColumn<Post, crate::models::PostStatus> {
    // A dot in the variant's `#[option(color = "…")]`.
    Post::columns().status.text().badge()
}

pub fn accent_column() -> ColorColumn<Theme, String> {
    Theme::columns().accent.color()
}
}

A cell can also link to a URL, copy its value, show a tooltip, cut a long value, show an icon or a placeholder for an empty value, and a table can tint a row by its record:

#![allow(unused)]
fn main() {
pub fn contact_table() -> Table<User> {
    let col = User::columns();
    Table::new((
        // Links to the user's page on another site, in a new tab.
        col.name
            .text()
            .url(|_, user: &User| Some(format!("https://people.example/{}", user.id)))
            .open_url_in_new_tab(),
        // A button copies the address; a long one shows its first 24 characters.
        col.email.text().copyable().limit(24),
        // The role's `#[option(icon = …)]` in place of its label.
        col.role.icon(),
    ))
    // A row whose user is inactive reads muted.
    .row_color(|_, user: &User| (!user.active).then_some(Color::Gray))
    .row_color_reading(Reads::of(lens!(User.active)))
}
}

A link takes a relative URL or an http, https, mailto or tel one, so a value a user wrote cannot turn into a script. A closure over the row may read any field: on a resource that restricts a field, it declares what it reads with .reading(..), or .row_color_reading(..) for the row color and RowLink::reading(..) for a row link, as a .description(..) does.

The export writes the formatted value: $1,234.50, not 123450. Numbers and money read in the request’s locale, 1 234,50 $ in French: Translations says how a catalog spells them. Over a decimal column, .numeric(..) and .money(..) spell the stored digits without passing through a float.

Editing in a cell

ToggleColumn, SelectColumn and TextInputColumn let a user change one field from the list, without opening the edit page:

#![allow(unused)]
fn main() {
pub fn triage_table() -> Table<Post> {
    let col = Post::columns();
    Table::new((
        // Saves on Enter.
        col.title.text_input(),
        // Each saves as soon as it changes.
        col.status.select(),
        col.featured.toggle(),
    ))
}
}

A cell posts its field alone to the record’s edit route, with the record’s version, so the save runs every check the edit page’s does, then lands back on the list. A refused value opens the edit page with its error. The control shows on a row the user may edit, for a field field access lets them change; anywhere else, and on the detail page, the cell shows the value.

The resource’s form must edit the field with the matching control: a checkbox or switch for a toggle, a choice over static options for a select, a one-line text field for a text input. The mount refuses the column otherwise, and when that control is disabled on edit or shows only while a condition holds, since the cell posts no other field for the condition to read.

Hiding columns

.toggleable() lets each reader hide a column from the list, and .hidden_by_default() starts it hidden until they show it. Every built-in column takes both:

#![allow(unused)]
fn main() {
pub fn user_table() -> Table<User> {
    let col = User::columns();
    Table::new((
        col.name,
        // Shown until a reader hides it.
        col.email.text().toggleable(),
        // Hidden until a reader shows it.
        col.created_at.date().hidden_by_default(),
    ))
}
}

A list with such a column renders a Columns menu in its toolbar. The panel keeps each signed-in user’s choice per resource, in the shipped ColumnPreference model, which tablo::models! registers. Hiding a column only declutters the list: search, sort and the export still read it, and the detail page shows it.

Presenting a derived column

A model whose default table fits but for a label, a badge or a hidden column keeps the derive and says so on the field, rather than declaring every column. Each #[columns(..)] key calls the builder of the same name on the column the field’s type picks, in the table and on the detail page, and filter adds the filter the type picks:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, toasty::Model, tablo::PanelModel)]
pub struct Invoice {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    // A badge in the variant's color, and a select filter over the variants.
    #[columns(badge, filter)]
    pub status: crate::models::PostStatus,
    // `€1,234.00`, labelled "Amount due".
    #[columns(label = "Amount due", money = EUR)]
    pub total: i64,
    // Hidden until a reader shows it, and a date range filter.
    #[columns(hidden_by_default, filter)]
    pub issued_at: jiff::Timestamp,
}
}

A key the column does not take, such as badge on a bool, fails to compile at the key. The derive’s page lists the keys and the filter each type picks.

Your own columns

A column is anything that implements Column<M>, from tablo::extend. The built-in columns implement it and nothing more, so a column of your own reaches as far as theirs:

#![allow(unused)]
fn main() {
pub struct Initials;

impl Column<User> for Initials {
    fn name(&self) -> &str {
        "initials"
    }
    fn label(&self) -> tablo::Text {
        "Initials".into()
    }

    // The export's cell, and the table's unless `cell` renders a view.
    fn text(&self, _cx: &Cx, u: &User) -> String {
        u.name
            .split_whitespace()
            .filter_map(|w| w.chars().next())
            .collect()
    }

    fn cell<'a>(&self, cx: &'a Cx, u: &User) -> BoxView<'a> {
        let text = self.text(cx, u);
        view! { <span class="font-mono">(text)</span> }.boxed()
    }
}

// Joins a table's tuple, as a built-in column does.
impl IntoColumns<User> for Initials {
    fn into_columns(self) -> Vec<Arc<dyn Column<User>>> {
        vec![Arc::new(self)]
    }
}
}

Only name, label and text are required; Column lists the methods that make it searchable, sortable, toggleable or loading a relation. A sortable column of your own is the table’s default sort through default_sort_by(Sort::desc("revenue")), which names it by its name. A default_sort(lens!(..)) takes any field of the model, whether or not a column shows it. Its IntoColumns impl puts the column in the tuple next to the built-in ones; without one, append it with Table::column(..), which also takes columns past the tuple’s twelve.

Search, sort and pagination

The URL holds the list’s whole state, so every view of a list is a link you can share:

?tab= picks a tab, ?q= searches, ?sort= and ?dir= sort, ?page= and ?per_page= page, ?f.<name>= filters and ?group_by= groups. Table has the parameters’ rules: how search matches, the default sort, and what an unusable filter does.

A table shows 25 rows per page unless .page_size(n) sets another size, and offers the reader a choice of sizes that .per_page_options([..]) changes. Each numbered page counts the result set, one more query, so a table too large to count, or one rows are written to while it is read, picks another Pagination: Simple drops the count, and Cursor pages by row, so no row is skipped or repeated when rows change between two pages.

.hide_search() removes the search box, and .hide_filter_menu() the filter menu. The list reruns as each filter changes; .deferred_filters() waits for the menu’s Apply button instead, so a reader sets several filters before one rerun.

Live updates

Every table updates in place: typing in the search box, choosing a filter, sorting and paging rerun the page with the new state, keeping focus and scroll position. Without JavaScript the links still navigate to the state they spell.

Filters

#![allow(unused)]
fn main() {
        .filters((
            // A checklist: the posts holding any checked status.
            SelectFilter::of(lens!(Post.status)).multiple(),
            TernaryFilter::new(lens!(Post.featured)).labels("Featured", "Not featured"),
            // Two date inputs: the first and the last day.
            DateFilter::new(lens!(Post.created_at)).range(),
            // The authors `AuthorResource` lists, by name.
            SelectFilter::relationship::<AuthorResource>(lens!(Post.author_id)).label("Author"),
        ))
}

SelectFilter matches one or more values of a field, TernaryFilter a bool, DateFilter a day or a range of days, NumberFilter a number or a range of them, TextFilter a term the user types, matched by what the field contains, starts or ends with, or equals, PresenceFilter whether an optional field holds a value, and QueryFilter named options, each a Toasty predicate you build:

#![allow(unused)]
fn main() {
pub fn filtered_user_table() -> Table<User> {
    User::table().filters((
        // Two number inputs: `?f.age.min=18&f.age.max=65`, both ends included.
        NumberFilter::new(lens!(User.age)).range(),
        // A term and how it matches: `?f.email=example.com&f.email.op=ends`.
        TextFilter::new(lens!(User.email)).matching([TextMatch::EndsWith, TextMatch::Is]),
    ))
}
}

A text filter ignores case as the search does: through ILIKE on PostgreSQL, the column’s collation on MySQL, and for ASCII letters only on SQLite and Turso. An active filter’s parameter is ?f.<name>=<value>, named after the field, and active filters combine with AND. Each filter’s page has its values and its options, such as .multiple() for a checklist or DateFilter::range for two bounds.

Filter a foreign key through SelectFilter::relationship: it offers and applies only the related rows the user may view, as a relationship choice does, where a plain SelectFilter over the key would reveal which keys exist.

A filter is anything that implements Filter<M>, from tablo::extend: a name, a label, the predicate a value selects, and the control the filter menu renders. The built-in filters implement it and nothing more.

#![allow(unused)]
fn main() {
pub fn promoted_filter() -> QueryFilter<Post> {
    QueryFilter::new("promoted", "Promoted")
        .option("Promoted", Post::fields().featured().eq(true))
        // `?f.promoted=backlog`, whatever the label reads.
        .option_keyed(
            "backlog",
            "In the backlog",
            Post::fields().featured().eq(false),
        )
}
}

FilterInput carries the parameter the control submits and the current FilterValue, and input.select(cx, options) renders the built-in select, input.checklist(cx, options) the built-in checklist. A control offering what a query loads overrides load_control, the async method the filter menu calls, which defaults to control. value.single() is the one value a single-choice control submits, value.values() every repeated value, and value.part("from") a part a control submits as ?f.<name>.from=, under input.part_param("from"):

#![allow(unused)]
fn main() {
pub struct Adults;

impl Filter<User> for Adults {
    fn name(&self) -> &str {
        "adults"
    }
    fn label(&self) -> tablo::Text {
        "Adults".into()
    }
    fn to_expr(&self, _cx: &Cx, value: &FilterValue) -> Option<Expr<bool>> {
        (value.single() == Some("yes")).then(|| User::fields().age().ge(18))
    }
    fn control<'a>(&self, cx: &'a Cx, input: FilterInput) -> BoxView<'a> {
        input.select(cx, vec![("yes".into(), "Adults only".into())])
    }
}
}

A filter of your own goes in the filters((..)) tuple; alone, it is a one-element tuple, .filters((Adults,)). Its name holds no ., which the parameter reserves for a part.

A filter that cannot apply is never dropped silently: the list shows a warning banner naming it, and the export refuses the request rather than export more rows than asked.

Tabs

Tabs above the toolbar offer the views of a list its readers switch between most, each a predicate of its own:

#![allow(unused)]
fn main() {
        .tab(ListTab::new("all", "All"))
        .tab(
            ListTab::new("drafts", "Drafts")
                .query(Post::fields().status().eq(PostStatus::Draft))
                .badge(),
        )
}

?tab=drafts shows a tab, and a list without ?tab= shows the first. A tab combines with the search and the filters, and the export and a selection of every matching record follow it. .badge() counts a tab’s rows under the current search and filters, one more query per badged tab. The panel reads the fields a tab’s predicate names off the predicate, so that field access hides the tab from a user who may not view one. ListTab has the rules.

A tab per option of an Options field is one call: all, then a counted tab per status, keyed by its value, so ?tab=draft lists the drafts:

#![allow(unused)]
fn main() {
pub fn status_tabs() -> Table<Post> {
    Table::new(Post::columns().title).option_tabs(lens!(Post.status))
}
}

Summaries

A summary counts records under the rows: every record the list selects, or those a predicate selects among them.

#![allow(unused)]
fn main() {
        .summary(Summary::count("Posts"))
        .summary(Summary::count("Featured").query(Post::fields().featured().eq(true)))
}

It counts in the database under the current tab, search and filters, across every page, one query per summary each time the list renders, and hides, as a tab does, from a user who may not view a field its predicate reads. Summary has the rules. Toasty offers no other aggregate yet, so a summary only counts: a sum or an average over the whole query waits for it.

Grouping

#![allow(unused)]
fn main() {
        .group_by(lens!(Post.status))
        .group_by(lens!(Post.featured))
}

Each .group_by(..) offers one grouping, which the toolbar’s Group by menu picks, and ?group_by=status, named after the field, spells. A grouping orders the query by its field ahead of the sort, so a group runs on across pages and its rows keep the sort within it; each group’s header shows its value, or “No value” over the rows holding none, and collapses and expands its rows. Selecting the page expands every group, so a bulk action never takes a row the reader cannot see. A list groups by nothing until the reader picks a grouping.

Export

The list header links Export CSV, which downloads the list as the reader sees it: the current search, filters and sort over every row of the resource’s query, and at most 10,000 rows by default (Limits::export_rows), never a truncated file. Table has the export’s rules.

Paging through a list and taking it whole are separate rights: the policy is asked Export on top of ViewAny, and refused, the button is hidden and the route answers 403. ReadOnly refuses it. A table that no one should export drops the button and the route:

Table::new(columns).without_export()

Import

A resource that creates through a form can import a CSV file too:

ResourceDef::new().importable()

The list header then links Import CSV for a request the policy allows to Create. The file’s header names the form’s keys, and each row is a create submission, checked by the same field access, rules, validate_record and record fn as the create page. Every row writes in one transaction, so one refused row writes nothing, and the page lists every refusal by row and column:

name,email,role
Barbara Liskov,barbara@example.com,admin

ResourceDef::importable has the file’s rules, its limits and what the hooks receive. The import reads what the form posts, not what the export writes, so an exported file does not import back.

Row actions and deletes

Each row shows View, Edit, Delete and the custom actions placed on rows, each as the policy allows it on that record. When the policy allows DeleteAny, or a custom action on the bulk bar, the list adds a checkbox column and a bulk bar, which shows in the toolbar once a row is selected. A row nothing can be done to gets no checkbox, so select-all only selects rows something can be done to.

A bulk delete skips the records the policy refuses and reports them in its notification. Both deletes ask first through a confirmation dialog, as in the header of the record’s detail and edit pages, and land back on the list as it was left. Table has the limits.

If the table fails to load, the list shows an error state with a retry link in place of the rows.