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

Introduction

Tablo is an admin toolkit for Rust. You declare, once per database model, its table, its form and who may see and change it; Tablo serves the list, create, edit, detail and delete pages for it, rendered on the server.

Tablo is a layer over two upstream projects:

  • Topcoat renders the HTML and owns routing, the request context Cx, reactivity, assets, cookies and sessions. The panel’s pages are Topcoat views, and your own pages use the same view!, #[component] and #[layout].
  • Toasty is the ORM. Tablo queries your Toasty models directly, so the model is the single source of truth for columns, relations and nullability.

What you get

  • Server-rendered pages, no SPA. There is no client build step and no WASM bundle. Topcoat’s runtime updates tables in place by rerunning the page on the server; without JavaScript, search, sort, filters and pagination still work as links and GET forms.
  • Typed declarations. Columns, form fields and filters name a model field with a lens such as lens!(User.email), so a renamed or retyped column is a compile error.
  • Checks at startup. Mounting the panel validates every declaration — a form struct that disagrees with its schema, two resources on one URL, a tenant-owned resource with no tenant column — and returns an error naming each mistake before the server takes a request; see Mount errors.
  • Safe defaults. Every policy predicate denies until you allow it, authentication is on, every panel POST verifies a CSRF token, and a tenant-owned resource is scoped to the request’s tenant at every query.

How to read this guide

Your first panel builds a complete, runnable panel in one file. Each later chapter covers one part of it:

ChapterCovers
Panel and routingthe panel builder, the routes it serves, custom and public pages
Resourcesthe Resource trait: naming, query scoping, writes
Tablescolumns, search, sort, filters, export, live updates, deletes
Formsthe record form, controls, validation, uploads, embedded values
Detail pagesthe read-only record page and related tables
Actionsrecord actions, header actions and their input
Policy, auth, tenancywho may see and change what
Data accessquerying Toasty from your own pages
Organizing an appwhere models, resources, panels and settings go as an app grows
Extension pointsthe traits for your own columns, filters, controls and option sources
Securitythe defaults and what your deployment must provide
Deploymentthe release binary, its asset bundle, migrations
Mount errorsevery declaration mistake mounting refuses, and its fix
Troubleshootingwhat goes wrong once the panel mounts
Testing and benchmarkstesting a panel over HTTP

The runnable reference is examples/showcase: every feature in this guide is exercised there. Terms are defined in CONTEXT.md and design decisions are recorded in docs/adr/. If this guide disagrees with the code, the code is right: please open an issue.

Your first panel

This chapter builds a complete admin in one file: a Book model, a resource for it, and the main that serves it with a login page. examples/quickstart is this app with writes opened and the stylesheet wired in.

Dependencies

An app depends on the tablo facade and picks its database driver with a tablo feature. It names topcoat and toasty directly for their macros, at the versions Tablo uses:

[dependencies]
tablo = { version = "0.11.1", features = ["sqlite"] }
topcoat = { version = "0.12", default-features = false, features = ["view", "router", "discover", "serve", "font", "font-fontsource", "asset"] }
toasty = { version = "0.11", default-features = false, features = ["jiff"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
uuid = "1.23"

The toolkit enables no driver itself: sqlite, postgresql, mysql and turso each turn on Toasty’s driver of the same name. The [workspace.dependencies] of Tablo’s Cargo.toml hold the pinned versions. tablo is the only Tablo dependency the app names, unless it builds its own stylesheet (The stylesheet): every path in this guide starts with tablo::, and the derives work through it.

The app

use tablo::{auth::create_admin, prelude::*};
use toasty::Db;
use topcoat::{
    Result,
    router::{Router, RouterBuilderDiscoverExt},
};

/// The model: every column the panel renders comes from this type, and
/// `ModelForm` writes `BookForm`, what the create and edit forms parse into.
#[derive(Debug, Clone, toasty::Model, tablo::PanelModel, tablo::ModelForm)]
pub struct Book {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    pub title: String,
}

pub struct BookResource;

impl Resource for BookResource {
    type Model = Book;
    type Form = BookForm;

    // The default policy denies everything; this one opens the list and
    // the records, and nothing else.
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new().policy(ReadOnly)
    }
}

#[tokio::main]
pub async fn main() -> Result<()> {
    let mut db = Db::builder()
        // `Book`, and the tables Tablo ships: the login's users and sessions among them.
        .models(tablo::models!(Book))
        .connect("sqlite::memory:")
        .await?;
    db.push_schema().await?;

    // One account to sign in with.
    create_admin(&mut db, "admin@example.com", "secret", "Admin").await?;

    let mut builder = Router::builder().discover().with(db);
    builder.panel(Panel::new("admin").resource::<BookResource>())?;
    let router = builder.build();

    topcoat::start(router).await?;
    Ok(())
}

Run it and sign in as admin@example.com / secret:

cargo run
# open http://127.0.0.1:3000/admin/books

What each part does

  • tablo::PanelModel gives Book its default table and detail page: a column per field a person reads, so id, which Toasty generates, is left out. See Tables.
  • tablo::ModelForm writes BookForm, the record form a submission parses into: one field per model field a person fills, so id is left out. The record form also lays out the form. See Forms.
  • impl Resource declares the panel’s pages for one model. A resource must name Model and Form; every other item has a default, and the default policy denies everything. See Resources.
  • tablo::models!(..) lists every model Toasty maps: the app’s, then the ones Tablo ships, the built-in login’s users and sessions among them. Built with toasty::models! instead, a Db missing one fails the mount with an error naming it.
  • db.push_schema() creates the tables, which suits a prototype. A production app runs toasty-cli migrations instead.
  • Router::builder().discover() starts the app’s own router: the app owns it, and the panel is one part of it. with(db) gives it the database every handler reads.
  • Panel::new("admin") is a panel at /admin, framed in the shell — sidebar, topbar, toasts — by a layout it registers itself.
  • resource::<BookResource>() registers the resource’s routes under /admin/books, adds its sidebar entry, and, because the panel has no home page, makes /admin redirect to the book list. Panel and routing lists every route.
  • .panel(..) checks every declaration and mounts the panel, or returns a MountError listing every mistake it found. build() returns the Router.
  • topcoat::start serves the router on HOST:PORT (default 127.0.0.1:3000) until Ctrl+C or SIGTERM.

What the example leaves out

  • Writes. ReadOnly allows only listing and viewing, so the create and export links are hidden, the create and edit pages answer 403, and rows show no Edit or Delete action. Policy, auth, tenancy opens them.
  • Styling. The example registers no asset bundle, so pages render unstyled and without the shell’s scripts, but every page and form works. The router’s .assets(..) and the panel’s shell_assets add the stylesheet, the font and the scripts; see Panel and routing. The stylesheet itself comes from the build script below.

The stylesheet

The panel’s markup carries Tailwind classes. tablo::ui::DEFAULT_STYLESHEET is Tablo’s prebuilt stylesheet: every class Tablo writes, on the default theme. Hand it to Panel::shell_assets and the app needs no build script and no Tailwind:

#![allow(unused)]
fn main() {
pub fn asset_panel(db: Db, bundle: AssetBundle) -> Panel {
    let _router = Router::builder().discover().with(db).assets(bundle);
    Panel::new("admin").shell_assets(tablo::ui::DEFAULT_STYLESHEET, GEIST)
}
}

It covers none of the app’s own classes. An app that writes Tailwind classes in its own pages, or changes a theme token, builds its own stylesheet instead, with tablo-build under [build-dependencies]:

[build-dependencies]
tablo-build = "0.11.1"

The app owns styles.css at its package root. The build imports Tailwind and Tablo’s default theme ahead of it, so the file names the app’s own sources and redeclares only the tokens it changes:

@source "./src/**/*.rs";

:root {
  --primary: oklch(0.45 0.18 265);
}

Theme tokens lists every token; each is declared under :root and again under .dark, in crates/tablo-build/src/theme/.

build.rs runs the build:

fn main() {
    println!("cargo::rerun-if-changed=build.rs");
    println!("cargo::rerun-if-changed=src");
    tablo_build::tailwind().expect("the Tailwind build runs");
}

tablo_build::tailwind() adds Tablo’s own sources to the build, wherever Cargo unpacked them, and writes $OUT_DIR/tailwind.css, which tailwind::stylesheet!() (under topcoat’s tailwind feature) hands to Panel::shell_assets in place of the prebuilt one. The stylesheet names no path into Tablo. The build downloads the Tailwind CLI on first run.

Panel and routing

A Panel is an admin panel: resources and pages under one prefix, one shell, one login. You configure it with builder calls and mount it on your app’s Topcoat router, which serves every registered resource and page, the login page, and the shell that frames them, beside your own routes.

#![allow(unused)]
fn main() {
use tablo::prelude::*;
use topcoat::{asset::RouterBuilderAssetExt, router::{Router, RouterBuilderDiscoverExt}};

pub fn admin_router(db: Db) -> topcoat::Result<Router> {
    let mut builder = Router::builder()
        .discover() // the app's own pages and routes, and Tablo's
        .with(db); // the toasty::Db every handler uses
    builder.panel(
        Panel::new("admin") // mounted at /admin
            .brand(Brand::new("Acme"))
            .home::<Dashboard>() // GET /admin
            .resource::<UserResource>() // /admin/users and its sub-routes
            .page::<ReportsPage>(), // GET /admin/reports
    )?;
    Ok(builder.build())
}
}

Routes

A resource with the slug users, on a panel mounted at /admin, serves its list at /admin/users, each record’s pages under /admin/users/{id}, and its list-wide routes, such as the create form and the CSV export, under /admin/users/-/. The - segment keeps those apart from a record’s, so a record whose key is create still has its detail page. A resource without a record form serves no form routes, and an action or a relation adds routes of its own. Panel::resource lists every route and when it is served.

A registered route is not an open one: each checks the resource’s policy (Policy, auth, tenancy).

The panel also serves its home page at /admin, its sign-in, and the auth pages Auth turns on. Every other path under /admin answers 404 behind the gate, so a visitor signs in before learning a path serves nothing. Panel lists those routes.

Builder reference

CallEffectSee
Panel::new(prefix)the panel at /{prefix} ("" mounts at /admin)
resource::<R>()registers a resource’s routes and sidebar entryResources
page::<P>()registers a page at /{prefix}/{slug}Pages
home::<P>()registers a page at /{prefix}Pages
brand(Brand)sets the name and optional logo in the sidebar, the topbar, and above the sign-in and sign-up cards, the optional favicon, and the themeBranding
dark_by_default()starts a first-time visitor darkBranding
environment(Environment)names the deployment, such as staging, on every pageBranding
login_hint(text)adds a line under the sign-in cardBranding
locales(locales)lists the locales the panel offers, the default first, English by defaultTranslations
translations(locale, ftl)adds the app’s Fluent catalog for a localeTranslations
time_zone(zone)sets the zone a user without their own reads and enters times in, UTC by defaultForms
user_menu_item(NavigationItem)adds an entry to the user menu, above Sign outThe shell layout
auth(Auth)replaces or disables the built-in password loginPolicy, auth, tenancy
uploads(uploader)sets where file fields store their bytesForms
serve_dir(path, dir)serves a directory of files, publicly unless the path sits under the panel prefixForms
uploads_dir(url_prefix, dir)stores file fields’ uploads in a directory and serves it at signed URLs that expireForms
shell_assets(css, font)adds the stylesheet, font and scriptsAssets
layout(render)frames the panel’s pages with your layout instead of the shellThe shell layout
content_security_policy(..), without_content_security_policy()replaces or drops the panel’s Content-Security-PolicySecurity
strict_transport_security(max_age)sends HSTS on the panel’s responsesSecurity

Mounting

builder.panel(panel) mounts a panel on a let mut builder = Router::builder() and returns its PanelHandle; the RouterBuilderPanelExt trait, in the prelude, provides it. The router is yours: discover your own pages and routes, install the Db with .with(db) and the asset bundle with .assets(..), then mount. The panel reads both from the router, so they come first, and it installs a layer with no path, so it comes after your own pathless layers; panel says why.

The builder calls never fail; .panel(..) returns a MountError listing every mistake instead: see Mount errors.

Several panels

One router mounts any number of panels at distinct prefixes, each with its own resources, pages, sidebar, brand and auth:

#![allow(unused)]
fn main() {
pub fn two_panels(db: Db) -> topcoat::Result<Router> {
    let mut builder = Router::builder().discover().with(db);
    builder.panel(
        Panel::new("admin")
            .resource::<UserResource>()
            .resource::<OrderResource>(),
    )?;
    builder.panel(
        Panel::new("portal")
            .brand(Brand::new("Customer portal"))
            .auth(Auth::custom(Customers))
            .resource::<OrderResource>(),
    )?;
    Ok(builder.build())
}
}

A resource registered by two panels is declared once: both serve the same table, form and policy, each under its own prefix. A panel’s prefix must not overlap another’s: /admin and /admin/reports are refused, /admin and /administration are not.

Each panel has its own login page, and a session belongs to the panel that signed the user in. A user signed in to /admin is anonymous on /portal, and signing in to /portal leaves the /admin session as it is: each panel has its own cookie, and signing out of one ends only that one. A page’s live updates run as the panel of that page alone, and a link into another panel is a full page load. See Policy, auth, tenancy.

URLs

The tablo::url helpers answer for the request’s panel, so app code never spells a prefix:

#![allow(unused)]
fn main() {
pub fn panel_urls(cx: &Cx) {
    let _ = tablo::url::resource::<PostResource>(cx); // Some("/admin/posts")
    let _ = tablo::url::page::<ReportsPage>(cx); // Some("/admin/reports")
    let _ = tablo::url::panel(cx); // Some("/admin")
}
}

A helper returns None where the panel serves no such page, such as for a resource it does not register, so a link to a page that does not exist never renders. A request outside every prefix, such as a public page, has no panel until it enters one with PanelHandle::enter; see Data access. tablo::navigation_item::<R>(cx) answers the same way with R’s whole sidebar entry, which suits a dashboard linking to lists.

A record’s pages and actions have helpers too, typed by the resource, so a job or a test spells no record path either. tablo::url lists them and when each answers None.

The shell layout

The panel frames every page under its prefix in the shell — sidebar, topbar and notification toasts — with a layout it registers itself, so declare no #[layout] of your own at the prefix.

  • The sidebar collapses to a rail of icons, each naming its entry on hover; below md it opens as a sheet instead.
  • The topbar holds the sidebar’s toggle and a trail to the page: the sidebar entry the page is under, then Create, View or Edit on a resource’s pages, the entry linking back to its list. Under an entry that is not a resource, such as the dashboard, a deeper page names its last path segment.
  • Error pages. A page load that fails with 404, 403 or 500 shows the failure inside the shell, with the trail ending in it and a link home, under the browser’s URL and with the error’s status. A request with another method, such as a form POST, keeps the bare status. A signed-in user the panel refuses outright sees a standalone 403 page with Sign out instead.
  • The user menu, in the sidebar’s footer, shows the signed-in user’s initials, their display_name and the subtitle their PanelUser returns, such as an email. It opens the theme choice, a Profile link when the panel has a profile page, the entries Panel::user_menu_item adds, and Sign out. The Profile link follows the page into an area that holds it. A panel with Auth::disabled() has no user to show, so its footer offers the theme choice alone.

To change the frame, pass your own layout function to Panel::layout. Panel::layout_shell is the shipped one, so a layout that keeps the shell calls it around its own markup; one that does not call it replaces the shell entirely:

#![allow(unused)]
fn main() {
pub fn admin_layout<'a>(cx: &'a Cx, slot: Slot<'a>) -> BoxView<'a> {
    let page = view! { <div class="acme-admin">(slot)</div> }.boxed();
    Panel::layout_shell(cx, page.into())
}

pub fn shell_panel() -> Panel {
    Panel::new("admin").layout(admin_layout)
}
}

Every resource and page gets one sidebar entry, labelled with its plural label (a page’s label) and linked to its list or page URL, unless it is hidden as described below. The sidebar lists an entry only when the request’s user may open it: a resource’s when its policy allows ViewAny, a page’s when its PageDef::access answers true. So a user never sees a link that would answer 403.

A resource that calls ResourceDef::without_navigation(), or a page whose def calls PageDef::without_navigation(), gets no entry. Its pages stay mounted and answer at their URLs under its policy or access check, but the topbar trail starts at the sidebar entry a page is under, so it has none for them unless another entry covers their path, such as the home page. Link such a page from the user menu with Panel::user_menu_item.

A resource sets the order and an icon on its def, and the panel resolves the URL:

#![allow(unused)]
fn main() {
impl Resource for UserResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .navigation_order(-1)
            .icon(tablo::ui::icons::USERS)
    }
}
}

A page sets the same icon, navigation_order and navigation_group on its PageDef. NavigationItem::at(label, url) links elsewhere, such as to a list with a filter applied, from ResourceDef::navigation or PageDef::navigation.

tablo::ui::icons names the Lucide icons the panel draws, its navigation entries included. An entry that wants another one stages the set its app’s own iconify_icon! resolves against: in the app’s build.rs,

fn main() {
    topcoat::icon::iconify::BuildConfig::new()
        .icon_set("lucide")
        .stage()
        .expect("the Lucide set stages");
}

and in the app, a constant beside the def that uses it:

#![allow(unused)]
fn main() {
use topcoat::icon::{IconData, iconify::iconify_icon};

pub const PACKAGE: IconData = iconify_icon!("lucide:package");
}

The app’s manifest needs topcoat with the icon-iconify feature in [dependencies], where the macro reads the staged set, and in [build-dependencies], where the build script stages it. The first build downloads the set through the shared cache. .cache_dir("assets/iconify") beside .icon_set_version("lucide", "1.2.137") stages a committed lucide.json and its lucide.version sidecar offline instead, since a pinned set is reused only while the two agree.

navigation_group("Content") on either def renders the entry in a labelled sidebar group, after the ungrouped entries.

An entry may carry a badge after its label. NavigationItem::badge("New") sets a fixed one; ResourceDef::navigation_badge(Post::fields().status().eq(PostStatus::Draft)) counts the rows of the resource’s scoped_query that the filter matches, so each tenant sees its own count. Each counted badge is a query on every sidebar render: navigation_badge says when it runs.

Areas

An app’s settings are many pages a user opens rarely: the account’s profile and sign-in, the tenant’s name, members and billing. An Area moves them out of the sidebar into a part of the panel with a sidebar of its own:

#![allow(unused)]
fn main() {
pub fn app_panel() -> Panel {
    Panel::new("app")
        .resource::<PostResource>() // GET /app/posts
        .area(
            Area::new("settings")
                .group("Account", |group| group.profile().two_factor())
                .tenant_group(|group| {
                    group
                        .tenant_profile_with(|def| def.slug("general").label("General"))
                        .resource::<UserResource>() // GET /app/settings/users
                }),
        )
}
}

The area mounts its resources and pages under /app/settings, each slug taken from the area’s own namespace. The panel’s sidebar lists the area as one entry, which opens the first of its entries the user may open; Area::without_navigation() leaves that entry out, for an area the user menu and the tenant menu lead into. Inside the area, the sidebar shows a link back to the panel’s home, then each group with the entries the user may open, and the trail starts at the area.

AreaGroup::profile, two_factor and tenant_profile move the pages auth serves into the group. The user menu and the tenant menu link them at their new URL, and the prefix no longer serves them. profile_with and tenant_profile_with adjust the moved page’s def, and take header actions there, which render in the form’s header: deleting the account, or the tenant, belongs on the page that edits it. A group added with Area::tenant_group is headed by the name of the tenant the request acts for, and shows nothing to a request that acts for none.

The topbar holds a search box over every resource the panel mounts. As the user types, it lists the first matches of each resource under its plural label, in the sidebar’s order, and links a results page at {prefix}/-/search?q= that lists more, which Enter opens. Cmd+K, or Ctrl+K, focuses the box from anywhere on the page.

A resource’s search reads what the resource already declares. A record matches when each word of the term is in one of its table’s searchable columns or in its record_title column, which also titles the result. The results are the records the resource’s list shows the same user: its policy, its tenancy, its trash and its field access apply as they do there, and each result opens the record’s detail page. global_search lists details under each title:

#![allow(unused)]
fn main() {
impl Resource for UserResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .record_title(lens!(User.name))
            .global_search(GlobalSearch::new().detail("Email", lens!(User.email)))
    }
}
}

ResourceDef::without_global_search() leaves one resource out, and Panel::without_global_search() removes the box and the results page. Panel::without_global_search and ResourceDef::global_search have the full rules.

Pages

A page that is not a record list — a dashboard, a report, a settings screen — implements Page. Its render defaults to the page its def declares: a header with the title, the description and the header action buttons, over the widget grid. A page that shows only those writes no render:

#![allow(unused)]
fn main() {
use tablo::{Page, PageDef, Panel};

pub struct ReportsPage;

impl Page for ReportsPage {
    fn declare() -> PageDef {
        PageDef::new().description("The figures behind each month's close.")
    }
}

pub fn reports_panel() -> Panel {
    Panel::new("admin").page::<ReportsPage>() // GET /admin/reports
}
}
  • The def. Page::declare returns a PageDef, as a resource’s returns a ResourceDef: the slug, the sidebar entry, the title and description, who may open the page, its header actions and its widgets. Panel::page_with::<P>(|def| …) adjusts the def for one panel:

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

impl Page for SalesPage { fn declare() -> PageDef { PageDef::new() .slug(“sales”) .icon(tablo::ui::icons::LAYOUT_DASHBOARD) .navigation_group(“Reports”) .access(is_manager) } }

/// The portal’s sales page sits first in the sidebar, outside the group. pub fn sales_portal() -> Panel { Panel::new(“portal”).page_with::(|def| def.navigation_order(-1)) }


- **Slug and label** default to the type name without its `Page` suffix: `ReportsPage` mounts at
`reports` and is labelled "Reports". `PageDef::slug` and `PageDef::label` change them. Pages and
resources share one slug namespace. The title defaults to the label; `PageDef::title` changes
it.
- **The home page.** `Panel::home::<P>()` mounts a page at the prefix itself instead of the
redirect to the first resource in the sidebar. A panel has at most one.
- **Access.** With authentication on, the page renders only for a signed-in user with panel access,
inside the shell layout. `PageDef::access(|cx| …)` narrows that: when it answers `false`
the page answers 403 and leaves the sidebar. It is synchronous, like a policy, and reads the
signed-in user with `auth::user::<U>(cx)`.
- **Actions.** `PageDef::header_action::<A>()` declares a [header action](./actions.md#header-actions),
behind the same sign-in and `access` as the page. The default `render` shows their buttons in
the header.
- **Forms.** Any other form a page renders posts to an app `#[route]`; put that route under the
panel prefix so the auth gate covers it. `access` does not cover that route, so the route
asks `can_open::<P>(cx)` itself: the panel's sign-in and the page's `access`, as the page's
`GET` checks them.

### Widgets

A dashboard is a grid of widgets. A `Widget` renders one block of it, and `PageDef::widget::<W>()`
adds it to the page's grid, which the default `render` shows under the header:

```rust
/// The orders the caller can see, and this week's revenue.
pub struct SalesOverview;

impl Widget for SalesOverview {
  fn declare() -> WidgetDef {
      WidgetDef::new().full_width()
  }

  async fn render(cx: &Cx) -> Result<impl View> {
      let orders = Stat::records::<OrderResource>(cx).await?;
      let revenue = Stat::new("Revenue", "$12,400")
          .detail("8% more than last week")
          .trend(Trend::Up)
          .color(Color::Success)
          .chart([9.1, 10.2, 11.0, 12.4]);
      Ok(tablo::stats(cx, orders.into_iter().chain([revenue])))
  }
}

/// Revenue per week, as a line.
pub struct RevenueChart;

impl Widget for RevenueChart {
  async fn render(cx: &Cx) -> Result<impl View> {
      Ok(tablo::chart(
          cx,
          Chart::line(["W1", "W2", "W3", "W4"])
              .heading("Revenue")
              .series(Series::new(
                  "Revenue",
                  [9_100.0, 10_200.0, 11_000.0, 12_400.0],
              )),
      ))
  }
}

/// The newest posts the caller can see, under the post list's columns.
pub struct LatestPosts;

impl Widget for LatestPosts {
  fn declare() -> WidgetDef {
      WidgetDef::new().access(can_list::<PostResource>)
  }

  async fn render(cx: &Cx) -> Result<impl View> {
      let table = RecordTable::new()
          .heading("Latest posts")
          .order_by(Post::fields().created_at().desc())
          .limit(5);
      tablo::record_table::<PostResource>(cx, table).await
  }
}

pub struct OverviewPage;

impl Page for OverviewPage {
  fn declare() -> PageDef {
      PageDef::new()
          .widget::<SalesOverview>()
          .widget::<RevenueChart>()
          .widget::<LatestPosts>()
  }
}
  • Stats. stats(cx, …) lays out a row of Stat tiles. Stat::records::<R>(cx) counts what R’s list would show the caller, through scoped_query, and links to it; it is None when the caller may not open that list, so the row has no tile for it. Stat::records_by_week::<R>(cx, created_at, weeks) adds a sparkline of the records created each week, one count query a week, so a dashboard never loads the table to draw it.
  • Charts. chart(cx, …) draws a Chart, a line or bar chart over shared labels with a Series of values per thing it measures, as SVG the server writes: it reads without JavaScript, and a table of its values stands in for it to a screen reader. A chart over a resource’s records reads them as any widget does, below.
  • Record tables. record_table::<R>(cx, …) lists a few of R’s records under its list’s own columns, or the ones RecordTable::column names by their field’s lens, with a link to the full list. It shows the records the list would, which RecordTable::filter narrows, in the RecordTable::order_by order, at most RecordTable::limit of them. Each row links its View and Edit pages as R’s policy allows, and the columns hide what R’s field access hides from the caller, as the list does. It never sorts, pages, searches or writes: the list does.
  • Who sees a widget. WidgetDef::access(|cx| …) leaves a widget out of the grid for the requests it refuses, and the grid renders nothing for a request the page refuses. A widget that reads a resource’s records asks can_list before it reads them, then reads them through scoped_query, which keeps the tenant and the resource’s query but not its policy.
  • Layout. PageDef::widget_columns sets how many columns the grid has on a wide screen, and WidgetDef::span and WidgetDef::full_width how many a widget spans. A narrow screen stacks every widget.
  • Above a resource’s list. ResourceDef::list_widget::<W>() adds a widget to a grid the list page renders above its table, for a banner or the figures behind the rows, without rewriting the page; ResourceDef::list_widget_columns sets its columns. The list’s sign-in and policy guard it, and it reruns with the list. list_query::<R>(cx) reads R’s records as the list shows them, under its tab, search and filters, so its figures follow what the reader narrows the list to; db::count(cx, query) counts them.
  • Filters. PageDef::filter(PageFilter::select(..)) and PageFilter::date_range(..) add a bar under the header, a form the page submits to itself that keeps each value in the query string, so a filtered dashboard is a link. page_filters(cx) reads the values in a widget: .choice("channel") is the option a select holds, and .date_range("period") the first and last day a range holds, either one open. A filter narrows nothing itself: the widget decides what a value means, and still reads its records through scoped_query or list_query. A page that renders itself places page_filter_bar::<Self>(cx).

Rendering a page

A page that shows more than its header and grid writes render:

#![allow(unused)]
fn main() {
use tablo::Page;
use topcoat::{Result, context::Cx, view::{View, view}};

pub struct ExportsPage;

impl Page for ExportsPage {
    async fn render(cx: &Cx) -> Result<impl View> {
        Ok(view! {
            tablo::ui::page(
                tablo::ui::page_header(tablo::ui::page_title("Exports"))
                tablo::ui::page_content(tablo::ui::card(tablo::ui::card_content("…")))
            )
        })
    }
}
}

Its render replaces the default whole, so it places the parts it keeps: header_action_buttons::<Self>(cx) in its page_actions, widgets::<Self>(cx) in its page_content. The def’s title and description are the default render’s, so it writes its own.

The tablo::ui composites give a page the same frame as the panel’s own pages: page sets the width and padding; page_header holds a page_title, an optional page_description and optional page_actions; page_content holds the body. Inside it, use card for a panel of content, stat for a dashboard figure, and empty_state for a region with nothing to show. They are styled by the design tokens (--card, --border, --primary, …) that a styles.css overrides, so one theme restyles the panel’s pages and yours.

Public pages

A page outside the panel prefix is an ordinary Topcoat #[page] on your router. The auth gate covers only the panel prefix and /_topcoat/runtime, so such a page is public.

A panel handle’s document renders the same HTML document as that panel’s shell — head, assets, favicon, theme — around your own markup, and its url gives the panel’s prefix for a link to it. A public page belongs to no panel, so it names the one whose shell it takes: keep the handle builder.panel(..) returns on the router. Under a prefix, Panel::document takes the request’s own panel.

#![allow(unused)]
fn main() {
/// The handle `builder.panel(..)` returned for the admin panel, which the router builder adds
/// with `.with(Admin(admin))` after mounting it.
pub struct Admin(pub tablo::PanelHandle);

// A layout wraps every route under its path: this one wraps /blog and /blog/{id}.
// A layout at "/" would wrap /admin too.
#[layout("/blog")]
pub async fn blog_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
    let Admin(admin) = topcoat::context::context::<Admin>(cx);
    admin
        .document(
            cx,
            "Blog",
            view! { <div class="mx-auto max-w-3xl px-6 py-10">(slot)</div> },
        )
        .await
}

#[page("/blog")]
pub async fn blog(cx: &Cx) -> Result<impl View> {
    Ok(view! { "Posts" })
}
}

A public page loads its rows with a plain Toasty query, not through a resource. The resource’s tenant scope applies only to the panel’s loaders, so in a multi-tenant app the page states its own tenant predicate. See Data access.

Branding and theme

#![allow(unused)]
fn main() {
pub fn branded_panel() -> Panel {
    Panel::new("admin")
        .brand(
            Brand::new("Acme")
                .logo("/logo.svg")
                .dark_logo("/logo-dark.svg")
                .favicon("/favicon.svg")
                .theme(Theme::Amber),
        )
        .dark_by_default()
        .login_hint("Demo: admin@example.com / password")
}
}
  • brand names the panel in the sidebar header, in the topbar on narrow screens, and above the sign-in and sign-up cards. The logo shows 32px square in the sidebar and 48px tall above the cards, with its own corners, so a mark drawn on a 16px grid stays sharp. A brand without a logo shows its first letter. dark_logo replaces the logo while the page renders dark, so a wordmark stays legible on either background. favicon links the icon of every page the panel renders, sign-in included; without it the browser asks for /favicon.ico.
  • dark_by_default() makes the panel start dark for a visitor who has not chosen a theme. The user menu offers light, dark and the system’s theme; the choice is kept in the tablo_theme cookie and wins over this default. Under the system’s theme, tablo-ui’s script mirrors the system’s scheme into tablo_scheme for the server to render. Without the call the panel starts light.
  • login_hint renders a muted line under the sign-in card, such as demo credentials.

Themes

Brand::theme dresses the panel, its sign-in pages included, in one of the themes Tablo ships. They share one grammar, so a panel reads as Tablo in any of them: the sidebar’s groups and the tables’ columns are headed by small captions, the current page is notched by a bar in the primary color, the page’s title is ruled off from its content by a line notched the same way, cards open on a ruled head band, a record’s entries are captions over their values, and a selected or hovered row is marked as with a highlighter. Each theme then sets that grammar in a voice of its own:

ThemeLooks like
Theme::Jade, the defaultthe ruled sheet: a jade primary on cool neutrals, the page a white sheet inset in the sidebar’s frame
Theme::Amberthe workshop: warm stone neutrals and an amber primary, bold titles, ringed cards, the current page an amber plate; close to Filament’s default look
Theme::Graphitethe instrument: black and white, barely rounded and flat, captions and figures in the monospace, gridded tables, beside a charcoal sidebar in either color scheme
Theme::Iristhe studio: a violet primary on tinted grays, pills for buttons, badges and tabs, soft violet shadows, the sidebar a card floating beside the page under a frosted topbar
Theme::LedgerTablo’s own site as a panel: ink on paper, square corners, a heavy grotesk over monospaced capitals, numbered sidebar groups, stamped buttons with a hard offset shadow, a red primary and a yellow highlighter

Each theme has a light and a dark palette, so the visitor’s choice of scheme still applies. A theme sets the tokens and the sidebar’s frame; the brand’s colors and radius, and the tokens an app’s styles.css redeclares, apply over it. The page sets in the font the app passes to shell_assets, except under Ledger, which ships its own faces (Schibsted Grotesk and Martian Mono) and links them from the panel’s assets.

Brand::sidebar frames the page another way than the theme does: SidebarFrame::Ruled, the sidebar flush with the window and ruled off from the page; SidebarFrame::Inset, the page a sheet inset in the sidebar’s color; or SidebarFrame::Floating, the sidebar a card beside the page.

Brand::new("Acme")
    .theme(Theme::Graphite)
    .sidebar(SidebarFrame::Floating)

Brand::look lets each request wear another theme or frame, such as one a visitor picks. It takes a function that answers a Look for every page the panel renders; the app stores the pick, usually in a cookie of its own, and reads it back there:

fn visitor_look(cx: &Cx) -> Look {
    match cookies(cx).get("acme_theme").as_ref().map(|cookie| cookie.value()) {
        Some("graphite") => Look::default().theme(Theme::Graphite),
        _ => Look::default(),
    }
}

Brand::new("Acme").look(visitor_look)

The themes are the set Tablo ships; there is no API to register another. An app that wants its own look redeclares tokens in styles.css over the theme closest to it.

Brand colors

A brand repaints the shipped theme without a stylesheet of the app’s own:

Brand::new("Acme")
    .color("oklch(0.55 0.2 270)")      // buttons, links, focus rings, the brand mark
    .dark_color("oklch(0.7 0.16 270)") // the same while the page renders dark
    .on_color("#ffffff")               // the text on them
    .radius(Radius::Large)             // every corner

Each page then carries a small <style> after the stylesheet, which redeclares --primary, --ring, --primary-foreground and --radius. A color is a hex color or a color function of plain arguments: mounting the panel refuses anything else (BrandColor), since the style sheet would carry it as it is.

Environments

environment(Environment::new("Staging")) draws a stripe along the top of every page of the panel, its sign-in pages included, and a badge hanging from its middle, in Color::Warning unless .color(..) picks another; the browser tab title starts with [Staging]. Read it from the deployment, and give production none:

let panel = match std::env::var("APP_ENV").as_deref() {
    Ok("production") => panel,
    Ok(name) => panel.environment(Environment::new(name.to_owned())),
    Err(_) => panel.environment(Environment::new("Local").color(Color::Info)),
};

Theme tokens

The shell’s colors, shadows and corner radius are CSS custom properties, declared under :root for the light scheme and again under .dark; a theme other than Jade redeclares them under [data-tablo-theme=…], which the shell writes on <html>, as specific as :root so the app’s :root still wins. An app that builds its own stylesheet redeclares the ones it changes in its styles.css (The stylesheet); Tailwind reads each as a color of the same name, such as bg-primary or text-muted-foreground, in the panel’s markup and yours.

TokenPaints
--background, --foregroundthe page and its text
--card, --card-foregroundcards, tables, dialogs and the sign-in and sign-up cards
--popover, --popover-foregroundthe option lists of selects and menus
--muted, --muted-foregroundsubdued surfaces and secondary text
--primary, --primary-foregroundprimary buttons and checked checkboxes
--destructive, --destructive-foregrounddelete buttons, errors, and the danger color
--success, --warning, --infothe success, warning and info colors of badges and tinted cells
--borderborders and dividers
--inputthe edges of inputs, selects, checkboxes and radios, a step stronger than --border
--ringfocus rings
--controlthe face of inputs, selects and outline buttons
--head, --rule, --rule-strongthe head bands of cards, sections and tables; the rules inside a surface; the rule under a table’s head and under the page’s title
--mark, --mark-strong, --mark-foregroundthe highlighter: hovered and selected rows, then text selection and <mark>
--shadow-xs, --shadow-sm, --shadow-md, --shadow-lgthe shadows of the same names: menus and dialogs take --shadow-lg
--shadow-card, --shadow-control, --shadow-buttonthe shadows of cards, inputs, and solid buttons
--radiusthe corners: rounded-lg, with rounded-md and rounded-sm 2px and 4px smaller and rounded-xl 4px larger
--sidebar, --sidebar-foregroundthe sidebar and its text
--sidebar-primary, --sidebar-primary-foregroundthe sidebar’s primary elements, --primary by default
--sidebar-accent, --sidebar-accent-foregroundthe hovered and active sidebar entry
--sidebar-border, --sidebar-ringthe sidebar’s borders and focus rings, --border and --ring by default

The font is --font-sans, under Tailwind’s @theme: the family shell_assets links, then the system’s sans-serif. The type of the grammar is set by --tablo-* properties a theme redeclares: --tablo-heading-weight, --tablo-heading-tracking and --tablo-title-size for titles, the --tablo-caption-* family for captions, --tablo-figure-* for a stat’s figure, and --tablo-notch for the width of the bar marking the current page.

Assets

Without assets the panel renders unstyled HTML without Topcoat’s runtime or the shell’s scripts: every page and form still works, tables update by navigating, and the confirmation dialogs that deletes and confirmatory actions go through do not open. To style it, install the app’s Topcoat asset bundle on the router, then give the panel the Tailwind stylesheet and the font the shell links:

#![allow(unused)]
fn main() {
pub const GEIST: Font =
    fontsource_font!(GEIST, weight: [400, 500, 600, 700], style: Normal, host: Asset);

pub fn asset_panel(db: Db, bundle: AssetBundle) -> Panel {
    let _router = Router::builder().discover().with(db).assets(bundle);
    Panel::new("admin").shell_assets(tablo::ui::DEFAULT_STYLESHEET, GEIST)
}
}

The shell preloads every face the font declares, so name the weights its stylesheet uses: 400 to 700 upright. Left out, fontsource_font! takes every weight in both styles, eighteen files for Geist, before the first paint. An italic the font lacks is slanted by the browser.

shell_assets also makes the shell load Topcoat’s runtime, which drives the live tables, the confirmation dialogs and the variant choice, and tablo-ui’s scripts: searchable selects, repeater rows, and the sidebar toggle and the theme choice. The stylesheet is Tablo’s prebuilt one, or the app’s own from tablo_build::tailwind() in its build.rs (Your first panel).

AssetBundle::load() reads the bundle from the assets directory beside the executable, which cargo build does not write. topcoat dev builds the app, writes the bundle there and serves the app; topcoat asset bundle --release writes it beside a release binary, and the two deploy together.

Resources

A resource declares the panel’s pages for one Toasty model: which rows it lists, how its table and form look, who may see and change a record, and how a write runs. You implement the Resource trait on a unit struct, return what it declares from declare() as one ResourceDef value, and register it with Panel::resource.

The smallest resource lists rows and shows each one, and writes nothing:

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

impl Resource for AuditResource {
    type Model = Audit;
    type Form = NoForm<Audit>; // list-only: no create or edit pages

    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            .policy(ReadOnly)
            .table(Table::new(Audit::columns().action))
    }
}
}

The model derives PanelModel, which reads what a person sees: a table column and a detail page column per field a column can show, whoever writes it. A resource with create and edit pages names a record form as its Form, which writes: the one #[derive(ModelForm)] writes for the model, or a #[derive(RecordForm)] struct, with one form control per field. Set the def’s table, form or detail to arrange or extend one; see Tables, Forms and Detail pages.

The definition

declare() returns a ResourceDef, and every setting has a default:

ResourceDef methodDefaultPurpose
table(..)the model’s PanelModel::table()the list’s columns, filters and options: Tables
form(..)every control, in declaration orderhow the create and edit forms arrange the record form’s controls: Forms
detail(..)the declared table’s columns, else the model’s PanelModel::detail()the detail page’s columns: Detail pages
without_page(ResourcePage::..)the list, the view page, and the create and edit pages of a resource with a record formturns the create or the view page off; the policy decides who may open a page, never whether it exists
record_title(lens!(..))the label and the record’s keythe detail page’s heading, each relationship option over the resource, which also searches the column, each global search result, and a RelationColumn::of cell
global_search(..), without_global_search()searched, each result titled alonethe details under each result in the panel’s global search, or the resource left out of it
public_link(..)nonethe record’s public page, linked from its detail and edit pages
relation(..)nonea related resource shown as a table on the detail and edit pages
action::<A>()nonea record action, on rows, the detail and edit pages and the bulk bar: Actions
header_action::<A>()nonean action on no record, in the list’s header: Actions
policy(..)Denywhat the user may do: Policy, auth, tenancy
tenancy(..)none: served to every tenant, which mounting refuses over tenant-owned rowshow rows belong to a tenant: Policy, auth, tenancy
create_column(..)nonea column an overridden create_record sets itself, once per column
slug(..), label(..), plural_label(..)from the type namesURLs and titles: Naming
icon(..), navigation_order(..), navigation_group(..), navigation(..), without_navigation()the default entrythe sidebar entry; without_navigation() leaves it out: Sidebar

The panel builds the def once when it mounts and serves that copy to every request. Panel::resource_with adjusts it for one panel, so the same resource can mount read-only in a second panel:

#![allow(unused)]
fn main() {
Panel::new("portal").resource_with::<PostResource>(|def| def.policy(ReadOnly))
}

Trait methods

Model and Form are required. The methods, each with a default, receive the request:

MethodDefaultPurpose
validate_record(cx, form)no errorsrules that need the whole parsed form
create_record, update_recordthe derived writethe create and update writes: Writes
delete_record, bulk_delete_recordsdelete by primary keythe delete writes
before_commit(cx, change, ex)nothingrows that commit with the write, such as an audit log: Hooks
after_commit(cx, change)nothingside effects once the write commits: Hooks

Naming

The names default from the type names, following Filament’s conventions: BlogPostResource over BlogPost serves blog-posts, titles a record “Blog post” and its list “Blog posts”. The plural rules are the pluralizer crate’s, which Toasty names its tables with. Set label to rename a record, and plural_label only when the rules guess wrong; ResourceDef::slug and its siblings have the defaults.

Scoping the query

ResourceDef::query narrows the rows every loader reads to the ones a predicate matches: the list, the export, the edit and delete handlers, relationship options and the detail page. Use it for the resource’s own row scoping. Each panel mounts its own def, so one panel can narrow a resource that another serves whole, such as a blog that serves the published posts only:

#![allow(unused)]
fn main() {
pub fn blog() -> Panel {
    Panel::new("blog").resource_with::<PostResource>(|def| {
        def.query(Post::fields().status().eq(PostStatus::Published))
    })
}
}

ResourceDef::query_fn builds the predicate from the request, to narrow the rows to the signed-in user’s own, and answers None for a request that reads them all:

#![allow(unused)]
fn main() {
pub fn desk() -> Panel {
    Panel::new("desk").resource_with::<PostResource>(|def| {
        def.query_fn(|cx| {
            // An editor reads every post, an author their own.
            (!editors_only(cx)).then(|| Post::fields().author_id().eq(signed_in_author(cx)))
        })
    })
}
}

A narrowing says which rows, and nothing else:

  • The tenant filter. For a tenant-owned resource the framework adds it beside the narrowings at every loader. See Tenancy.
  • Soft deletes. Declare the column instead; see Soft deletes.
  • Relations. The list, the export and the detail page load the relations their columns declare: a RelationColumn declares its own, and a ComputedColumn declares one with include_unscoped. A CountColumn loads nothing and counts each row in the database. ResourceDef::include_unscoped loads a relation with every row, for one every loader reads, for example because the policy does.

In your own code, load a resource’s rows with scoped_query::<R>(cx)?, not Query::all(): it applies the panel’s narrowings, adds the tenant filter and leaves out the trashed records, and returns an error rather than an unscoped query. A background job builds its context from the mounted panel’s PanelHandle; see Outside a request.

The unique-value check on forms reads each narrowing: one that names a field of the #[unique] index stays in its probe, and one that names none is left out, so a value held by a row the narrowing hides is refused under its field. The query rustdoc has the rule.

Soft deletes

A resource that keeps deleted records names the column a delete stamps, a nullable timestamp:

#![allow(unused)]
fn main() {
            .soft_delete(lens!(Post.deleted_at))
}

A delete then sets the column to the current time instead of removing the row, and every loader leaves the stamped records out. The list’s filter menu gains a Trashed control, and a trashed record offers Restore and Delete permanently, which the policy allows through Ability::Restore and Ability::ForceDelete. In your own code, scoped_query_in::<R>(cx, Trashed::Only) loads the trashed records. ResourceDef::soft_delete has the rules, and the hooks receive the writes as Change::Restore and Change::ForceDelete.

Field access

A field only some users may see, or only some may change, declares who:

#![allow(unused)]
fn main() {
            .field_access(lens!(User.age), FieldAccess::new().view(is_admin))
            .field_access(lens!(User.role), FieldAccess::new().edit(is_admin))
}

Each rule asks about the request, not the record, and it binds the field of its model: every resource the panel mounts over that model obeys it. A user view refuses sees the field nowhere the panel shows its records, and one edit refuses sees its control disabled. ResourceDef::field_access lists every place the rule reaches.

The panel cannot see inside a closure, so a ComputedColumn and a TextColumn with a description say which fields they read, and on a panel that restricts a field the mount refuses one that does not. A QueryFilter, a tab and a summary need not: the panel reads the fields off their predicates.

ComputedColumn::new("Pay", |_, e: &Employee| e.salary.to_string())
    .reading(Reads::of(lens!(Employee.salary)))

A related record shows through the resource it names, which applies the restriction: RelationColumn::new::<R> names the fields its closure reads, and RelationColumn::of::<R> shows the record’s title. A declaration that would show a restricted record the panel cannot mask, such as RelationColumn::unscoped, fails to mount. So does a closure over the row beside a column loading such a record, unless it declares it reads only the row’s own fields: it then reads a copy of the row without its relations, which the derived PanelModel builds; FieldAccessFault lists each case.

Writes

Every create, update and delete runs in a transaction the framework opens. For an update or a delete, the handler first loads the target record through the scoped query inside that transaction and checks policy on it. It then calls the resource’s record function with the open transaction as ex.

create_record and update_record default to writing the record form’s fields (write_create and write_update), so most resources declare neither. To check something inside the transaction, override the function and delegate. This one refuses to move a comment onto a post that is not published:

#![allow(unused)]
fn main() {
impl Resource for CommentResource {
    type Model = Comment;
    // …
    async fn update_record(
        cx: &Cx,
        record: Comment,
        posted: Posted<CommentForm>,
        ex: &mut dyn toasty::Executor,
    ) -> Result<Comment, WriteError<CommentForm>> {
        if !posted.named(|f| f.post_id) || posted.post_id == record.post_id {
            return tablo::write_update::<Self>(cx, record, posted, ex).await;
        }
        let post = Post::filter_by_id(posted.post_id)
            .first()
            .exec(&mut *ex)
            .await?;
        if !post.is_some_and(|post| post.status == PostStatus::Published) {
            return Err(WriteError::<CommentForm>::field(
                |f| f.post_id,
                "Comments go on published posts",
            ));
        }
        tablo::write_update::<Self>(cx, record, posted, ex).await
    }
}
}

Run every statement through ex, and use the record you are given rather than loading it again: it is the row the policy check passed. Both functions return the written row, or a WriteError, which rolls the transaction back: Refused renders the form again with each error under its field, Declined renders it again with a message that names no field above the fields, and Failed answers as a failed write does. Return the derived write as it is: write_create and write_update answer a WriteError too.

A rule that reads the database refuses here rather than in validate_record, which runs before the transaction opens and gets no executor: a stock level, a quota, or a uniqueness no index models. A rule the write itself enforces, such as an update filtered on the stock it needs that matches no row, holds against a concurrent write. The CSV import lists a row its record fn refuses or declines with the other refused rows, and rolls that row back to a savepoint, so the rows after it are checked without its writes.

delete_record deletes the row by its primary key, or stamps it on a resource that soft-deletes, and bulk_delete_records calls it once per record, so overriding delete_record covers both. A bulk delete skips the records the policy refuses, as a bulk action does. A delete, a restore or a force delete that must not happen, such as a paid invoice’s, returns Err(WriteError::declined("..")): the transaction rolls back and the message flashes.

Hooks

Every write the panel makes for a resource reaches two hooks with a Change that says what it wrote: a create, an update, a delete or bulk delete, a restore or force delete, an action, or an attach or detach on a many-to-many relation. Neither runs when the write was refused or failed.

before_commit runs inside the transaction, after the record function or the action wrote, with the transaction as ex. A row written through ex commits with the write or not at all, so an audit log belongs here:

#![allow(unused)]
fn main() {
pub async fn before_commit(
    _cx: &Cx,
    change: &Change<Post>,
    ex: &mut dyn toasty::Executor,
) -> Result<()> {
    let action = match change {
        Change::Create(post) => format!("created {}", post.title),
        Change::Update { before, after } => {
            format!("updated {} (was {})", after.title, before.title)
        }
        Change::Delete(posts) => format!("deleted {} posts", posts.len()),
        Change::Restore(posts) => format!("restored {} posts", posts.len()),
        Change::ForceDelete(posts) => format!("deleted {} posts for good", posts.len()),
        Change::Action { name, records } => format!("ran {name} on {} posts", records.len()),
        Change::HeaderAction { name } => format!("ran {name}"),
        Change::Export { rows } => format!("exported {rows} posts"),
        Change::Attach {
            owner,
            relation,
            key,
        } => {
            format!("linked {} to {relation} {key}", owner.title)
        }
        Change::Detach {
            owner,
            relation,
            keys,
        } => {
            format!(
                "unlinked {} from {relation} {}",
                owner.title,
                keys.join(", ")
            )
        }
    };
    toasty::create!(Audit {
        action,
        created_at: jiff::Timestamp::now().to_string(),
    })
    .exec(ex)
    .await?;
    Ok(())
}
}

An error rolls back the write and every row the hook wrote, and the request fails with the write’s failure toast. Run every statement through ex: db(cx) or Notifications::send opens a second connection, which writes outside the transaction and, on a pool of one, waits forever.

after_commit runs once the transaction commits, before the response. Put work outside the database there, such as email, webhooks and cache invalidation, so a rolled-back write never triggers it:

#![allow(unused)]
fn main() {
pub async fn after_commit(cx: &Cx, change: Change<Post>) -> Result<()> {
    if let Change::Create(post) = &change {
        notify_subscribers(cx, post).await?;
    }
    Ok(())
}
}

An error it returns is logged and the write stays committed, and a crash between the commit and the hook skips it, so a row that must exist whenever the write does is written in before_commit.

An audit trail over every resource of a panel registers one CommitHook on the panel instead of a before_commit on each resource, so a resource added later cannot be left out. It runs inside the same transaction, after the resource’s own hook, and receives a PanelChange: the resource’s slug and label, and the Change with each record named by its key, its URL and the fields the write changed, each spelled before and after it as the model’s default table spells it. Its foreign keys and TenantId fields, which that table leaves out, are spelled as stored, so moving a record to another owner or tenant shows:

impl CommitHook for Audit {
    async fn before_commit(cx: &Cx, change: &PanelChange, ex: &mut dyn Executor) -> Result<()> {
        for record in change.change().records() {
            // record.url(), and for each field: field.name(), field.before(), field.after()
        }
    }
}

Panel::new("admin").before_commit::<Audit>()

Change lists what each variant carries, and what a change does not say, such as the links a form wrote. The audit example’s match lists every variant without a _ arm, so a kind of write a later Tablo adds breaks the build instead of going unaudited.

A Change carries every column, including fields the user’s field access hides, and so do a PanelChange’s fields, but for those the model marks #[columns(skip)]. An audit table that lower-privilege users can read should store only what they may see.

The profile and tenant-settings pages save their own rows and reach neither hook.

The audit log

A panel that needs an audit trail without writing one turns on the shipped log, from the tablo-audit crate, which the facade’s audit feature re-exports as tablo::audit:

tablo = { version = "0.11.1", features = ["sqlite", "audit"] }
use tablo::audit::PanelAuditExt;

Panel::new("admin").audit_log(|log| log.policy(when(is_admin)))

Every write of the panel then stores an AuditEntry per record it names, inside the write’s transaction, so a write whose entry fails rolls back with it. An entry keeps the user who did it, the tenant they acted for, the resource’s slug, the record’s key and page, and the fields the write changed, as a PanelChange spells them: a field marked #[columns(skip)] is never stored. The app lists the model in its models!, as tablo::models!(Post, tablo::audit::AuditEntry); mounting refuses a Db without it.

The trail also keeps what auth does on the panel, on no resource:

EntryWhen
sign_ina session opens: by password, by a provider, after the second factor, on sign-up
sign_in_failedthe panel refuses a sign-in; the entry keeps the login as typed
second_factor_failedthe password was right and the code wrong
sign_outthe user signs out
credentials_changedthe profile page saves a new password
password_reseta mailed reset link sets a password
email_changedthe link mailed to a new address is confirmed
two_factor_enabled, two_factor_disabled, recovery_codes_replacedthe two-factor page
impersonate, stop_impersonatingacting as a user

A sign-in, and every change of a credential, commits with its entry or not at all. A refused sign-in, a wrong code and a sign-out go through when the entry cannot be stored, and the failure is logged. A refused sign-in names no user, since a wrong password and an unknown login read alike, and an attempt past the throttle stores nothing. Anyone who reaches the login page can add entries by failing to sign in, and someone who types their password in the login field leaves it in the log: prune on a schedule, and give the log a narrow policy. These entries carry no tenant but for what a signed-in user does, so in a panel with tenants only a reader who acts outside every tenant sees a sign-in. A sign-in the app does itself under Auth::external is recorded when the panel opens its own session for it; the app’s own login page records its failures.

The log is a read-only resource at {prefix}/audit-log, newest first. It is denied until customize gives it a policy, and whatever that policy says, its pages never write. A reader sees the entries of their own panel and tenant, about the resources whose list they may open; a field field access hides from them reads “Hidden”. The resource’s own row scope, such as a query that lists only the user’s own orders, does not narrow the log: give the log a policy no wider than the narrowest scope of the resources it records.

A tenant’s trail belongs with its settings. audit_trail() keeps the entries without listing them, and an area group lists the log as it lists any resource, at {prefix}/{area}/audit-log:

Panel::new("app")
    .audit_trail()
    .area(Area::new("settings").tenant_group(|group| {
        group
            .tenant_profile()
            .resource_with::<AuditLog>(|log| log.policy(when(manages_members)))
    }))

Mounting refuses an AuditLog on a panel without audit_trail(), where it would list nothing.

Values are stored as the writer read them, in their language and time zone, so an entry is a snapshot rather than data to compute on. A delete stores every field the record held, so data an app erases on request also lives in the log until it is pruned; mark such a field #[columns(skip)], or prune on the schedule the app’s retention rules set. Erasing an account, audit::forget_actor keeps its entries without its name, and erasing a tenant, audit::forget_tenant deletes the tenant’s entries but its impersonations. AuditEntry::impersonation() reads a start or a stop back typed, and audit::impersonations() filters a resource of AuditEntry to them.

A CSV export stores an entry too, with how many rows it handed over, before the first byte leaves: an export whose entry cannot be stored is refused. The entry says the file was asked for, not that the download finished.

An app records its own events, a report or a payment, with AuditEvent, through a hook’s executor or the panel’s Db. Nothing deletes entries but tablo::audit::prune(&handle, age), which a job calls on the schedule the app keeps them for.

The log uses nothing an app cannot: a commit hook, an AuthHook for what auth does, ResourceDef::restrict to stay read-only, mounted_resources to mask what its reader may not see, Panel::require_model and Panel::default_translations. A feature of the app’s own that reads across resources builds on the same calls.

Startup checks

Mounting the panel builds each resource’s def once and binds its table, form and detail page to the database schema. It refuses a resource whose declaration cannot work, such as a unique() field with no unique index, a column nothing writes on create, or a relation to a resource the panel does not register, and lists every mistake it found in one MountError: see Mount errors.

An action’s NAME is checked when the app compiles: ResourceDef::action and ResourceDef::header_action do not compile an action whose name is not one URL segment.

A modifier on the wrong kind of field does not compile: each Field constructor returns its control’s builder (TextField, ChoiceField, FileField, CustomField), which offers only that control’s modifiers.

A form control from elsewhere does not compile either: ResourceDef::form takes a Schema<R::Form>, which places only the record form’s own controls(), so a control of another form, or a field built with Field::text, is a type error rather than a refused mount.

The panel serves the checked def to every request, so declare() never reads the request: decisions about the user or the tenant belong to the policy and to the trait methods.

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.

Forms

A resource with create and edit pages declares a record form, the typed struct a submission parses into. The record form also gives each field its control, and ResourceDef::form arranges them. A resource that wants one control per field, in declaration order, declares no form at all.

The record form

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Copy, PartialEq, Eq, toasty::Embed, tablo::Options)]
pub enum Role {
    #[option(icon = tablo::ui::icons::USER)]
    Admin,
    #[option(icon = tablo::ui::icons::USERS)]
    Member,
}

#[derive(Debug, Clone, tablo::RecordForm)]
#[form(model = User)]
pub struct UserForm {
    pub name: String,
    pub email: String,
    #[form(options, blank = Role::Member)]
    pub role: Role,
    #[form(blank = 0)]
    pub age: i64,
}
}

Each field names a model field and has that field’s type, so renaming or retyping a column breaks the build. A field is either a scalar — String, a typed value, an Options enum, or an Option of one — bound to the one key its control posts, an embedded value marked #[form(embed)], or a repeater marked #[form(repeat)].

Leave out the columns the form does not write: the tenant column of a tenant-owned resource, which the framework sets on create, and columns with a Toasty #[default(..)] or #[auto].

Required and blank values. The record form alone decides which fields are required. A field’s blank answer is what it stores when its control is submitted empty, such as None for an Option. A field with no blank answer is required: the panel renders its control required, and an empty submission is refused inline. #[form(required)] takes the blank answer from an Option, so a nullable column such as a product’s SKU is still filled through the form. RecordForm lists each type’s blank answer and every #[form(..)] key.

The resource names the struct as its Form and, to arrange the controls, places them from the derive’s controls() in a Schema<UserForm>:

#![allow(unused)]
fn main() {
impl Resource for UserResource {
    type Model = User;
    type Form = UserForm;

    fn declare() -> ResourceDef<Self> {
        let c = UserForm::controls();
        ResourceDef::new()
            .form(Schema::new(Section::new("Profile").schema((
                c.name.placeholder("Ada Lovelace"),
                c.email.email(),
                c.role,
                c.age,
            ))))
            // .table(..), .policy(..) …
    }

    fn validate_record(_cx: &Cx, form: &UserForm) -> FieldErrors<UserForm> {
        let mut errors = FieldErrors::<UserForm>::new();
        if form.age < 0 {
            errors.add(|f| f.age, "Age must be zero or more");
        }
        errors
    }
}
}

A Schema<UserForm> takes only UserForm’s controls: a control of another form, or a field built with Field::text, does not compile there. A control the schema does not place follows the ones it does, in declaration order, so a form that adjusts one control places only that one: .form(Schema::new(c.email.email())). An unplaced control renders on its own after the schema’s last block, outside every section; a form arranged in sections places every control. Any control takes an app’s own input with .custom(control): see Custom controls.

A resource with a record form serves a create page, whoever its policy lets in, so mounting the panel refuses it unless every non-nullable column is filled by the form, by Toasty, by the tenant stamp, or by an overridden create_record whose def names it with create_column. A resource whose records arrive another way declares .without_page(ResourcePage::Create): it serves the edit page, no create page, and skips the check. A resource whose create page should also take a CSV file declares .importable().

A form from the model

When the record form is the model’s fields a person fills, derive tablo::ModelForm on the model and it writes the struct, named after the model:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, toasty::Model, tablo::ModelForm)]
pub struct Note {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    #[index]
    pub tenant_id: TenantId,
    pub title: String,
    #[form(optional)]
    pub body: String,
    #[default(jiff::Timestamp::now())]
    pub created_at: jiff::Timestamp,
    #[index]
    #[form(relationship = AuthorResource)]
    pub author_id: uuid::Uuid,
    #[belongs_to(key = author_id, references = id)]
    pub author: toasty::Deferred<Author>,
}
}

NoteForm holds title, body and author_id, with NoteFormField and NoteFormControls beside it. The derive leaves out what no person fills, such as the key and the tenant column, and author_id is in only because #[form(relationship = AuthorResource)] opts the foreign key in: without it, a create would leave the column unset, which mounting refuses. ModelForm lists what it leaves out and how to opt a field in or out.

Declare a #[derive(RecordForm)] struct instead when a form field is not a model column, such as a many-to-many field’s list of keys, or when the model should not name a resource. Move the field keys onto it and drop ModelForm from the model, or give one of the two another name: both are NoteForm by default.

Controls

The derive picks each field’s control from its type and its #[form(..)] key, as RecordForm lists: a bool is a toggle, #[form(options)] a choice, and a field with no key a text field. controls() hands each one over ready for its modifiers, so an override arranges rather than rebinds:

#![allow(unused)]
fn main() {
pub fn account_layout() -> Schema<UserForm> {
    let c = UserForm::controls();
    Schema::new((
        Section::new("Account").schema((c.email.email(), c.role)),
        Grid::new(2).schema((c.name, c.age)),
    ))
}
}

The role control already offers Role’s options: #[form(options)] chose a choice over the list of the field’s type. A closed set of values is a unit enum deriving toasty::Embed, which Toasty stores in one column, and tablo::Options, which gives the form, the filter and the column one list of options:

#![allow(unused)]
fn main() {
pub fn role_fields() {
    Field::choice(lens!(User.role)).options(Role::options());
    SelectFilter::of(lens!(User.role));
}
}

Each variant posts its snake_case name and reads as that name in sentence case, unless a catalog translates it; Options has the attributes that override either. A column, the detail page and a group header read a variant’s label, and a query compares the variant itself: User::fields().role().eq(Role::Admin). An Option<Role> field works the same way, reading an empty submission as None. An enum field without #[form(options)] gets a text field, which accepts only an option’s value. An enum leaf of an embedded value is such a text field, and its column shows the value.

Toasty stores the variant itself, under its snake_case name unless #[column(variant = "..")] renames it; the option’s value only spells it in forms and URLs. Moving a String column to an enum is therefore a schema change: rows whose text is not Toasty’s name for a variant no longer load.

A String field takes the same list with #[form(options = T)]. .options takes Vec<(String, String)> (an Options enum’s list), Vec<String>, or [&str; N] (["admin", "member"]).

A Vec of an Options enum with #[form(options)], or a Vec<String> with #[form(options = T)], is a multiple choice: a checkbox per option, and Toasty stores the chosen ones in one list column.

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Copy, PartialEq, Eq, toasty::Embed, tablo::Options)]
pub enum Topic {
    Releases,
    Security,
    Events,
}

#[derive(Debug, Clone, toasty::Model)]
pub struct Subscriber {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    pub email: String,
    // A list column: one value per chosen option.
    pub topics: Vec<Topic>,
}

#[derive(Debug, Clone, tablo::RecordForm)]
#[form(model = Subscriber)]
pub struct SubscriberForm {
    pub email: String,
    #[form(options)]
    pub topics: Vec<Topic>,
}

pub fn subscriber_layout() -> Schema<SubscriberForm> {
    let c = SubscriberForm::controls();
    Schema::new((c.email, c.topics.min_items(1).buttons()))
}
}

No option checked stores the empty list, so .min_items(1) is how the field requires a choice; .max_items(n) caps it, and .buttons() renders a compact list of toggles. RecordForm has the rules.

A Vec<String> marked #[form(tags)] takes what the user types instead: a checkbox per value it holds and per suggestion, then a text input adding values separated by commas.

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, toasty::Model)]
pub struct Snippet {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    pub title: String,
    pub labels: Vec<String>,
}

#[derive(Debug, Clone, tablo::RecordForm)]
#[form(model = Snippet)]
pub struct SnippetForm {
    pub title: String,
    // Any label the user types, with the topics as suggestions.
    #[form(tags, options = Topic)]
    pub labels: Vec<String>,
}
}

ChoiceField::tags has the rules.

Layout blocks arrange fields: Section::new(title) is a titled card, Group::new() an untitled container, and Grid::new(cols) a grid of 1 to 12 columns. A schema or block takes a tuple of at most twelve children; nest a Group for more.

A section can say what its fields are for and where they sit. .description adds a line under the title and .icon an icon before it; .aside() puts both beside the fields on a wide screen, so a long form reads as a list of topics. .collapsible() lets the title fold the fields away, and .collapsed() opens the page with them folded, for fields the user rarely changes:

#![allow(unused)]
fn main() {
pub fn account_sections() -> Schema<UserForm> {
    let c = UserForm::controls();
    Schema::new((
        Section::new("Account")
            .description("How the user signs in.")
            .icon(tablo::ui::icons::USERS)
            .aside()
            .schema((c.email.email(), c.role)),
        Section::new("Profile")
            .collapsed()
            .schema(Grid::new(2).schema((c.name, c.age))),
    ))
}
}

A folded section’s fields still post, and a section holding a field error renders open. Section has the full rules.

A grid stacks its children in one column until it is wide enough for its columns, so a form reads the same on a phone. A block or a field takes .span(n) to cover n of its grid’s columns, and .span_full() to cover them all. A three-column grid whose first section spans two puts the fields the user edits most in a main column and the rest in a sidebar beside it:

#![allow(unused)]
fn main() {
pub fn account_sidebar() -> Schema<UserForm> {
    let c = UserForm::controls();
    Schema::new(
        Grid::new(3).schema((
            Section::new("Profile")
                .span(2)
                .schema(Grid::new(2).schema((c.name.span_full(), c.age))),
            Section::new("Account").schema((c.email.email(), c.role)),
        )),
    )
}
}

Grid has the widths at which each grid lays out its columns.

Tabs::new shows one Tab at a time. Each tab’s fields still render and post while another tab shows, so splitting a long form into tabs changes what the user sees, not what the form submits. A tab’s trigger can lead with an icon and close with a badge, which a color dots:

#![allow(unused)]
fn main() {
pub fn account_tabs() -> Schema<UserForm> {
    let c = UserForm::controls();
    Schema::new(Tabs::new([
        Tab::new("Account")
            .icon(tablo::ui::icons::MAIL)
            .schema((c.email.email(), c.role)),
        Tab::new("Profile")
            .icon(tablo::ui::icons::USER)
            .badge("New")
            .badge_color(tablo::Color::Info)
            .schema(Grid::new(2).schema((c.name, c.age))),
    ]))
}
}

A refused submission reopens on the first tab holding an error, and the browser opens the tab of a control it refuses itself. Tabs has the full rules.

Wizard::new walks the user through its Steps in order, with a button to the next step and one back. The next step opens once the browser’s own checks pass on the current one, and Enter in a field moves forward rather than saving. As with tabs, every step’s fields render and post, and the form’s own buttons save from any step:

#![allow(unused)]
fn main() {
pub fn account_wizard() -> Schema<UserForm> {
    let c = UserForm::controls();
    Schema::new(Wizard::new([
        Step::new("Account").schema((c.email.email(), c.role)),
        Step::new("Profile").schema(Grid::new(2).schema((c.name, c.age))),
    ]))
}
}

A refused submission reopens on the first step holding an error. Wizard has the full rules.

Fields are what controls() hands over, and what a page’s or an action’s schema builds from a Toasty field lens:

ConstructorColumnControlBuilder
Field::text(lens)String, a typed value, or an Option of one<input>, or <textarea> with .multiline(rows)TextField
Field::choice(lens)any<select> over static options or a relationshipChoiceField
Field::rich_text(lens)String holding HTMLan editor with a toolbar: see Rich textRichTextField
Field::file(lens)String holding the file’s pathfile input: see File uploadsFileField
Field::files(lens)Vec<String> holding the files’ pathsfile list: see Several files per fieldFileField
Field::toggle(lens)boolcheckboxCustomField
Field::custom(lens, control)String, a typed value, or an Option of oneyour own Control: see Custom controlsCustomField

Every field takes .label(..), which defaults to the column name in sentence case. Whether a control is required is not the control’s to say: on a create or edit page the panel renders it required when its record-form field has no blank answer (a file input only while nothing is stored). Outside a panel no record form applies, and every control renders optional. Each constructor returns its control’s builder, which offers only that control’s modifiers, so a modifier on the wrong control does not compile:

TextField, ChoiceField, RichTextField and CustomField list each builder’s modifiers, such as .url(), .relationship::<R>(), .switch() or .accepted(). A multiple choice is required through ChoiceField::min_items, since its blank answer is the empty list. A choice needs something to offer, so mounting refuses a resource form’s or an action input’s choice with neither options nor a relationship.

Custom controls

A Control, from tablo::extend, renders the input of a custom field: a record form’s text control turned custom with .custom(control), or a Field::custom field. .custom (like .choice()) replaces the control with its modifiers, so email, unique and options set before it no longer apply. The field keeps everything fields share — the key, the label, the required marker, the error slot and the chrome around the input — and the control renders only the input, from a ControlInput carrying the key, the current value and the validation state:

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

impl Control for Color {
    fn render<'a>(&self, cx: &'a Cx, input: ControlInput) -> BoxView<'a> {
        let attrs = input.attributes(cx); // id, name, value, required, aria-*
        view! { <input type="color" (attrs)> }.boxed()
    }
}

// A record form's text control takes it with `.custom`; a page's field with `Field::custom`.
pub fn accent_control() -> CustomField<ThemeForm> {
    ThemeForm::controls().accent.custom(Color)
}

pub fn accent_field() -> CustomField {
    Field::custom(lens!(Theme.accent), Color)
}
}

A control renders only the form; the detail page shows the value through a column. The submission is read like any other field’s: the value posted under the field’s key, the last one when it is posted twice, parsed by the record form. Field::toggle is built this way: Toggle renders a hidden false before the checkbox under the same name, so an unchecked box submits false rather than nothing, and a bool record-form field reads an empty submission as false.

Typed values

A text control binds more than strings. Over a typed column it renders the stored value in the input its type names, and the record form parses the submission back through the type. A value the type refuses is an inline error naming it: `twelve` is not a valid whole number.

Integers and floats get a number input, the jiff civil types and Timestamp a date or time input; TypedValue lists each type’s input.

An amount that must stay exact, such as a price, is a decimal column. The tablo features rust_decimal and bigdecimal bind rust_decimal::Decimal and bigdecimal::BigDecimal, and turn on Toasty’s feature of the same name, which stores them:

[dependencies]
tablo = { version = "0.11.1", features = ["sqlite", "rust_decimal"] }
rust_decimal = "1"

A decimal gets a number input and keeps the scale it was typed with, so 12.50 is stored as 12.50. A spelling the type cannot hold exactly, such as an exponent or more decimals than Decimal carries, is an inline error rather than a rounded value.

A decimal column is not sortable by default: SQLite, MySQL and Turso store a Decimal as text, and every driver stores a BigDecimal as text, so the database would order 10.00 before 9.50. The PanelModel derive leaves it unsortable; declare .sortable() only on PostgreSQL with Decimal.

Implement tablo::extend::TypedValue to bind your own type: it names the type in errors, picks the input, and parses and spells the value, with a default for each item but the name.

Time zones

A datetime-local input posts a wall-clock time without a zone, so the panel places it in the request’s zone: tablo::time_zone(cx) answers the signed-in user’s PanelUser::time_zone, else the panel’s Panel::time_zone, else UTC.

#![allow(unused)]
fn main() {
pub fn paris_panel() -> Panel {
    let paris = jiff::tz::TimeZone::get("Europe/Paris").expect("the zone database names it");
    Panel::new("admin").time_zone(paris)
}
}

A timestamp’s control therefore shows the stored instant as the user’s own wall-clock time, and a DateColumn or DateFilter reads the user’s own day: 14:00 entered in Paris on 20 October stores 12:00:00Z. The stored value stays the instant, which the export spells in UTC. time_zone has the rules for skipped and repeated times, offsets, and custom controls.

Length, bounds and patterns

A text field declares the rules a value keeps. Each renders as the HTML attribute of the same name, so the browser checks it before it submits, and the server checks it again; a refused value is an inline error, and nothing is written. A value the record already stores is not checked again, so a rule added over existing rows does not lock them.

#![allow(unused)]
fn main() {
pub fn checked_account_form() -> Schema<UserForm> {
    let c = UserForm::controls();
    Schema::new((
        c.name.min_length(2).max_length(80),
        c.email.email().pattern(r".+@example\.com"),
        c.role,
        c.age.min(18).max(130),
    ))
}
}

TextField has each rule’s details: what a length counts, which types take a bound, and the regular-expression syntax a pattern shares between the server and the browser. A rule that cannot work, such as a minimum above its maximum, fails the mount.

A text field also compares with another field of its form: .gt(&other), .gte, .lt and .lte order two numbers, dates or times, and .different(&other) refuses an equal value, as ends_on.gte(&starts_on) keeps a stay from ending before it starts. Only the server checks them, in the same round as the other rules; TextField::gt has the rules. A rule these do not express belongs in Resource::validate_record.

Email, URL and uniqueness

.email() refuses what is not an address, and .url() what is not an http or https URL: the browser’s own check accepts a javascript: URL, which a link to the stored value would run.

A text field over a column with a unique index checks uniqueness before the write, and reports a taken value inline; .unique() states it explicitly. The database index stays the final check, so a unique field over a non-nullable column must be required, or every empty submission would store the same value. TextField::unique says what a concurrent write answers on each database.

Relationships

A choice over a foreign key loads its options from the related resource. Mark the record-form field #[form(relationship = AuthorResource)]; the form arranges and labels its control like any other:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, tablo::RecordForm)]
#[form(model = Post)]
pub struct PostAuthorForm {
    // The source whose scoped query loads the options; each is labelled by its `record_title`.
    #[form(relationship = AuthorResource)]
    pub author_id: uuid::Uuid,
}

pub fn author_control() -> ChoiceField<PostAuthorForm> {
    PostAuthorForm::controls()
        .author_id
        .searchable()
        .label("Author")
}
}

Each option’s value is the related record’s primary key, and its text the record’s title: the column the related resource’s record_title names, else its label and the key. Typing into a searchable choice matches that column and the related table’s searchable columns. A source that is not a resource implements OptionSource, including its label. .relationship_labelled::<R>(|cx, a| ..) labels one field’s options otherwise, to tell apart records that share a title.

Options follow the related resource’s tenant scope and policy, and a submitted key must be one of them, checked again inside the write’s transaction, so a hand-crafted POST cannot point at another tenant’s row. Past 200 options a .searchable() choice turns into type-to-search. ChoiceField::relationship has the rules.

Many-to-many fields

A many-to-many relation stores one row per pair in a join model with a belongs_to to each side. The model reaches the other side through it with a #[has_many(via = ..)] field:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, toasty::Model, tablo::PanelModel)]
pub struct Article {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    pub title: String,
    #[has_many]
    pub taggings: toasty::Deferred<Vec<Tagging>>,
    // The tags the join rows reach.
    #[has_many(via = taggings.tag)]
    pub tags: toasty::Deferred<Vec<Tag>>,
}

#[derive(Debug, Clone, toasty::Model, tablo::PanelModel)]
pub struct Tag {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    pub name: String,
    #[has_many]
    pub taggings: toasty::Deferred<Vec<Tagging>>,
    #[has_many(via = taggings.article)]
    pub articles: toasty::Deferred<Vec<Article>>,
}

/// The join model: one row per article and tag.
#[derive(Debug, Clone, toasty::Model)]
#[key(article_id, tag_id)]
pub struct Tagging {
    #[index]
    pub article_id: uuid::Uuid,
    #[belongs_to(key = article_id, references = id)]
    pub article: toasty::Deferred<Article>,
    #[index]
    pub tag_id: uuid::Uuid,
    #[belongs_to(key = tag_id, references = id)]
    pub tag: toasty::Deferred<Tag>,
}
}

The record form names that field, typed as a Vec of the related records’ keys, and marks it with the related resource:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, tablo::RecordForm)]
#[form(model = Article)]
pub struct ArticleForm {
    pub title: String,
    // Named like the `via` field, holding the keys of the tags it reaches.
    #[form(relationship = TagResource)]
    pub tags: Vec<uuid::Uuid>,
}

pub fn article_layout() -> Schema<ArticleForm> {
    let c = ArticleForm::controls();
    Schema::new((c.title, c.tags.searchable()))
}
}

The control is a checkbox per record the related resource offers. A create links the new record to each chosen one, one join row each, and an edit adds and deletes rows to match, unlinking only the records its form could offer. An overridden create_record or update_record links only by delegating to write_create or write_update. Making the two keys the join model’s primary key, #[key(article_id, tag_id)] as above, has the database store each pair once. RecordForm has the rules, the option cap and what the mount refuses.

Dependent choices

.depends_on(&field, column) narrows a relationship choice to the related records whose column equals the value another field of the same form posts: the cities of the chosen country.

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, tablo::RecordForm)]
#[form(model = Address)]
pub struct AddressForm {
    #[form(relationship = CountryResource)]
    pub country_id: uuid::Uuid,
    #[form(relationship = CityResource)]
    pub city_id: uuid::Uuid,
}

pub fn address_layout() -> Schema<AddressForm> {
    let c = AddressForm::controls();
    // The cities whose `country_id` is the chosen country.
    let city = c
        .city_id
        .depends_on(&c.country_id, City::fields().country_id());
    Schema::new((c.country_id, city))
}
}

When the parent changes, the browser fetches the new options, and a submission must name a record of the parent value it posts. ChoiceField::depends_on has the rules and what the mount refuses.

Filtered choices

.options_where(|cx| predicate) narrows a relationship choice to the related records a predicate selects, whatever the form posts: only the categories without a parent may be one.

c.parent_id
    .options_where(|_cx| Category::fields().parent_id().is_none())

The predicate is built for each request, so it may read the user or the tenant, and it narrows a dependent choice’s records too. The server checks a submitted key against it on submit and again in the write’s transaction. ChoiceField::options_where has the rules and what the mount refuses.

.creatable() lets the user create the related record without leaving the form: a link beside the select opens the related resource’s create page in a dialog, and the record it saves becomes the choice. The form keeps what was typed in it.

#![allow(unused)]
fn main() {
pub fn creatable_author_control() -> ChoiceField<PostAuthorForm> {
    // A "New" link beside the select opens the authors' create page in a dialog.
    PostAuthorForm::controls()
        .author_id
        .searchable()
        .creatable()
}
}

The dialog runs the related resource’s own create page; ChoiceField::creatable has the rules and what the mount refuses.

Help, disabled controls and defaults

Every control but a repeater takes .help(text), rendered under it, and .disabled() or .disabled_on_edit(). A text, choice or custom control also takes .default(value), the value the create form starts with: any form scalar, or a &str in the form spelling. A multiple choice’s default is an array or Vec of them: .multiple().default(["email", "sms"]).

#![allow(unused)]
fn main() {
pub fn account_form() -> Schema<UserForm> {
    let c = UserForm::controls();
    Schema::new((
        c.name.help("As it appears on invoices."),
        c.email
            .disabled_on_edit()
            .help("The sign-in address: it cannot change once the account exists."),
        c.role.default(Role::Member).disabled(),
        c.age.default(18_i64),
    ))
}
}

A disabled control posts nothing, so an edit keeps the stored value and a create stores the default, else the blank answer; .disabled() on a field with neither cannot mount, since no create could fill it. A default seeds the create form, where the blank answer is what an empty submission stores. Each modifier’s page has its rules, such as default.

A record form’s field also takes .hidden_on_create() or .hidden_on_edit(), which renders nothing for it on that form. Here an invite sets the address once and the role only once the account exists:

#![allow(unused)]
fn main() {
pub fn invite_form() -> Schema<UserForm> {
    let c = UserForm::controls();
    Schema::new((
        c.name,
        c.email.hidden_on_edit(),
        c.role.hidden_on_create(),
        c.age,
    ))
}
}

The server reads a hidden field as it reads a disabled one: a create stores its default, else its blank answer, and an edit keeps the stored value.

Conditional fields

.visible_when(&field, values) shows a field only while another field of the same form posts one of values: an option’s value, or true or false for a toggle. A Section, Group or Grid takes it too, for every field it holds:

#![allow(unused)]
fn main() {
#[derive(tablo::RecordForm)]
#[form(model = User)]
pub struct AccessForm {
    #[form(options, blank = Role::Member)]
    pub role: Role,
    pub sso_managed: bool,
}

pub fn access_layout() -> Schema<AccessForm> {
    let c = AccessForm::controls();
    let sso = c.sso_managed.visible_when(&c.role, ["admin"]);
    Schema::new(Section::new("Access").schema((c.role, sso)))
}
}

visible_when borrows the watched field, so build the condition before the schema takes it.

The browser shows and hides the field as the watched one changes, with no request, and the panel reads a submission the same way, dropping a hidden field’s key. A conditional field therefore needs a blank answer. visible_when has the rules and what the mount refuses.

.disabled_when(&field, values) keeps the control on the page but disables it while the watched field posts one of values: a member’s account cannot be SSO-managed.

#![allow(unused)]
fn main() {
pub fn locked_access_layout() -> Schema<AccessForm> {
    let c = AccessForm::controls();
    let sso = c.sso_managed.disabled_when(&c.role, ["member"]);
    Schema::new((c.role, sso))
}
}

While the condition holds, the server reads the field as it reads a .disabled() one, so a create stores its default and an edit keeps the stored value. The condition reads what the submission posts, so it is no access check: field access is. disabled_when has the rules and what the mount refuses.

Submitting

Every error renders inline in one round, with nothing written: the parse, the controls’ rules, relationships and uniqueness together, then validate_record once every field parses, keyed by the record form, each error picking its field by name (errors.add(|f| f.age, "Age must be zero or more")). A POST carrying a key the form does not declare answers 400, so a client cannot write role or tenant_id; an edit writes only the fields it posted; and a model with a #[version] field refuses a save another save overtook. RecordForm has the rules.

The create page has a second button, Create & create another, for entering several records in a row: it runs every check above, and a save lands back on the create form with the success flash, its fields at their defaults. From a relation table’s create link, the next form keeps the owner preselected.

The form page’s script saves on Ctrl+S (Cmd+S on macOS), and asks before a followed link, a reload or a closed tab drops what the user typed; a refused save asks from the start, since its values are the user’s. The browser’s back and forward buttons leave without asking. Without JavaScript the form posts as it renders and the page leaves without asking.

To write more than the form holds, override create_record or update_record (Resources) and use the builders: form.into_create() is the model’s create builder with every form field set, and posted.into_update(&mut record) is the update builder with one assignment per posted field, or None when nothing was posted.

Rich text

A rich text field edits HTML through a toolbar and stores it in a String or Option<String> column. A record form’s text control becomes one with .rich_text(), and a panel whose field of another type does refuses to mount; a page or an action input builds one with Field::rich_text(lens) or Field::rich_text_input(name):

#![allow(unused)]
fn main() {
pub fn post_content_form() -> Schema<crate::resources::PostForm> {
    let c = crate::resources::PostForm::controls();
    Schema::new((
        c.title,
        c.body
            .rich_text()
            .toolbar(&[
                &[Tool::Bold, Tool::Italic, Tool::Link],
                &[Tool::Heading2, Tool::BulletList, Tool::OrderedList],
            ])
            .placeholder("The full story…")
            .max_length(20_000),
        c.status,
    ))
}
}

The toolbar is the schema: the editor registers only the elements its tools produce, and the server cleans every submission down to them, so a <script> or a javascript: link never reaches the column. A text column moving to rich text needs its values rewritten through tablo::rich_text::from_text first. RichTextField has the rules.

RichTextColumn::new(lens) shows the value on a detail page as formatted HTML, and in a table and an export as its text. It cleans the value again as it renders, keeping what any Tool produces, since a seed or another app can write the column. A page of your own renders a stored value through tablo::rich_text::clean, unescaped, and reads its text through tablo::rich_text::text.

File uploads

A file field (#[form(file)] on a record-form String, or Field::file on a page) binds a String column that stores the file’s path or URL, never its bytes; a file list binds a Vec<String> of them (Several files per field). A form with a file field is sent as multipart/form-data, with a 10 MiB body limit (larger answers 413) that Panel::limits raises with Limits::body_bytes. Filenames are reduced to a safe basename before anything sees them.

Where the bytes go is your app’s decision; a panel whose resource form declares a file field refuses to mount without an Uploader. Panel::uploads_dir installs the stock one, a DirUploader, and serves its directory:

#![allow(unused)]
fn main() {
pub fn uploads_panel(dir: PathBuf) -> Panel {
    Panel::new("admin").uploads_dir("/uploads", dir)
}
}

It writes each file into the directory as {uuid}-{basename}, within the filesystem’s 255-byte name limit, and stores its URL: /uploads/ and the name as one percent-encoded path segment. The directory answers that URL only with a signature that expires, which the panel adds wherever it links or shows a stored file; a page of your own adds it with url::file(cx, &path). Once a write commits, it deletes the files the write let go: those of a deleted record, and the one an edit replaced or cleared; a soft delete keeps them until the force delete. The upload of a form that never saved, such as one refused for another field that the user then left, is deleted after 24 hours.

A file field takes any file until it declares .extensions(["png", "jpg"]) or .max_bytes(n). The server refuses a file either rule refuses before the uploader sees it, and the extensions also reach the browser’s file picker as accept. The extension is what is checked, not the content: a served file’s type comes from its extension, so the extension decides how a browser treats it. FileField::extensions has the rules.

The field is one panel: a drop area to click or drop files on, then the stored file and the files picked or dropped before the form saves them, each with a round button removing it. .image() shows them as tiles of their images; it changes what the field shows, not what it takes, so pair it with .extensions. Without JavaScript a click on the drop area still opens the browser’s file picker.

Any other store implements Uploader. This one refuses a file whose first bytes are not a PNG’s or a JPEG’s signature, which no field rule checks, then stores through the DirUploader that Panel::uploads_dir_with hands it, so its files still answer only at signed URLs. It forwards keep and delete too: the inner uploader deletes a file nothing kept after a day. A signature is no proof the rest is an image: decode the file when that matters.

#![allow(unused)]
fn main() {
/// Refuses bytes that do not start as a PNG or JPEG image, then stores like `uploads_dir` does.
struct ImagesOnly(DirUploader);

impl Uploader for ImagesOnly {
    async fn store(&self, cx: &Cx, filename: &str, bytes: &[u8]) -> Result<String, String> {
        let png = bytes.starts_with(b"\x89PNG\r\n\x1a\n");
        let jpeg = bytes.starts_with(&[0xff, 0xd8, 0xff]);
        if !png && !jpeg {
            return Err("the file is not a PNG or JPEG image".to_string());
        }
        self.0.store(cx, filename, bytes).await
    }

    async fn holds(&self, cx: &Cx, path: &str) -> bool {
        self.0.holds(cx, path).await
    }

    async fn keep(&self, cx: &Cx, path: &str) -> Result<(), String> {
        self.0.keep(cx, path).await
    }

    async fn delete(&self, cx: &Cx, path: &str) -> Result<(), String> {
        self.0.delete(cx, path).await
    }
}

pub fn images_panel(dir: PathBuf) -> Panel {
    Panel::new("admin").uploads_dir_with("/uploads", dir, ImagesOnly)
}
}

store returns the value to save, and its error is shown to the user, so keep it free of paths. The edit form keeps a stored file until the user removes it, and a form that re-renders with errors reuses an upload only under the tag the panel signed for its field, where Uploader::holds vouches for the path. Uploader has the rules, and Security the headers served files carry.

Several files per field

#[form(file)] on a Vec<String>, or Field::files on a page, makes a file list: the column stores one path per file, in the order the form lists them. Its input takes several files at once, which a save adds after the stored ones, and each stored file has its own remove checkbox, so the list works without JavaScript. With it, each file also has Move earlier and Move later buttons and can be dragged, by its grip on a touch screen, and the list saves in the order it shows. Files dropped on the input’s zone join the ones already picked, and .image() shows every stored and picked file as a thumbnail. Only the remove checkbox drops a stored file: a file another save added while the form was open stays. The extensions and size apply to each file, and max_files bounds how many the list holds once a save adds its files; choosing more than that stores none:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, toasty::Model)]
pub struct Album {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    pub title: String,
    pub photos: Vec<String>,
}

#[derive(Debug, Clone, tablo::RecordForm)]
#[form(model = Album)]
pub struct AlbumForm {
    pub title: String,
    #[form(file)]
    pub photos: Vec<String>,
}

pub fn album_form() -> Schema<AlbumForm> {
    let c = AlbumForm::controls();
    Schema::new((
        c.title,
        c.photos.image().extensions(["png", "jpg"]).max_files(12),
    ))
}
}

A refused save keeps the files it stored, as a single file field does, so the user drops one and saves again. Every file still shares the one form body limit, so a list of large files needs a raised Limits::body_bytes. Field::files has the rules.

Embedded values

A Toasty #[derive(Embed)] struct or enum is stored in its parent’s row as flattened columns (seo_title, seo_description). Derive EmbeddedForm on it and the form binds the whole value:

#![allow(unused)]
fn main() {
pub struct Seo {
    pub title: String,
    #[form(multiline = 3)]
    pub description: String,
}

// In the def's form: one call renders a control per field.
pub fn seo_schema() -> Section {
    Section::new("SEO").schema(Seo::form(Post::fields().seo()))
}

// In the record form: the value is one field.
#[derive(Debug, Clone, tablo::RecordForm)]
#[form(model = Post)]
pub struct PostForm {
    pub title: String,
    #[form(embed)]
    pub seo: Seo,
}
}

Every field of the value is a scalar, or a nested value marked #[form(embed)]; an enum renders a choice of variant and the chosen variant’s fields. On the detail page, Post::columns().seo shows each field under its own label. EmbeddedForm has the rules: which fields are required, which variant a submission reads, the attributes, and what a value cannot hold.

A resource’s form places an embedded value whole, as its record form’s control. A page’s schema can bind a single embedded field on its own by its path: Field::text(lens!(Post.seo.title)) binds the flattened seo_title column, as soon as the field is built.

Repeaters

Toasty stores a #[document] list of embedded structs in one column. Derive FormInput on the struct and mark the record-form field #[form(repeat)]: the form renders a row of the item’s controls per item, which the user adds, removes and moves.

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, toasty::Embed, tablo::FormInput)]
pub struct RecipeStep {
    #[form(multiline = 2)]
    pub instruction: String,
    #[form(blank = 0)]
    pub minutes: i64,
}

#[derive(Debug, Clone, toasty::Model, tablo::PanelModel)]
pub struct Recipe {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    pub title: String,
    // Stored in one column.
    #[document]
    pub steps: Vec<RecipeStep>,
}

#[derive(Debug, Clone, tablo::RecordForm)]
#[form(model = Recipe)]
pub struct RecipeForm {
    pub title: String,
    #[form(repeat)]
    pub steps: Vec<RecipeStep>,
}

pub fn recipe_form() -> Schema<RecipeForm> {
    let c = RecipeForm::controls();
    Schema::new((c.title, c.steps.label("Method").add_label("Add step")))
}

pub fn recipe_view() -> Detail<Recipe> {
    Detail::new(Recipe::columns().steps.repeater().label("Method"))
}
}

An item’s fields are scalars, declared like an action input’s with the FormInput attributes, and a field with no blank answer is required in every row. Each row posts its item’s fields under its own prefix, such as steps.0.minutes, and an edit that does not post the repeater keeps the stored rows. Adding, removing and moving rows needs JavaScript. Field::repeater has the rules and the limits.

Detail pages

A detail page shows one record, read-only, at GET /admin/{slug}/{id}. A resource declares it with ResourceDef::detail: a Detail of the same columns a table lists, arranged in Section, Group, Grid and Tabs blocks, which the panel builds once when it mounts. Each column reads its value off the typed record, and declares the relations it reads:

#![allow(unused)]
fn main() {
impl Resource for PostResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .detail({
                let col = Post::columns();
                Detail::new(Section::new("Post").columns((
                    col.title,
                    col.body,
                    col.status,
                    RelationColumn::of::<AuthorResource>(relation!(Post.author)),
                )))
            })
    }
}
}

The page adds a View action to each row, and without_page(ResourcePage::View) turns it off. Mounting refuses a resource that serves the page with a detail listing no column. ResourceDef::detail says what the page’s header carries, what it loads and what it answers for a record the request may not see.

The default detail page

Without detail, the model’s PanelModel give the detail page, as they give the table: one column per field the table lists, plus its embedded values and lists, in declaration order. It reads the model, not the record form, so a field Toasty writes, such as a #[default] timestamp, shows too, and a NoForm resource has a detail page as well. The derive’s page lists the column each type gets and the fields it leaves out.

A resource that declares a table and no detail page shows the table’s columns there instead, in the table’s order, so a column declared once for the list, such as a RelationColumn or a formatted amount, reads the same on the record’s page.

A relation shows only through a column that includes it, as Author does above, and a file path shows as text until a FileColumn links it. A resource declares its own detail page to pick or arrange the columns:

#![allow(unused)]
fn main() {
pub fn audit_view() -> Detail<Audit> {
    let col = Audit::columns();
    Detail::new((col.action, col.created_at))
}
}

What the page shows

The header carries the record’s title, its actions, Delete and Edit, each as the policy allows them on this record. A resource that declares a record page or a relation tab adds the record’s navigation under the header. Below it come the detail’s columns, then the related tables.

Each column renders its label over its cell, as it renders in a table, never a control. A ComputedColumn shows anything the record determines, such as a reading time:

#![allow(unused)]
fn main() {
pub fn reading_time() -> ComputedColumn<Post> {
    ComputedColumn::new("Reading time", |_, post: &Post| {
        let words = post.body.split_whitespace().count();
        format!("{words} words, {} min", words.div_ceil(200))
    })
}
}

An app’s own Column renders its cell on the detail page too; Detail::column appends one, and an IntoDetail impl for its type places it in a block. A column that shows more than one value under one label overrides entry, which renders the label over the cell by default; EmbeddedColumn overrides it to give each leaf its own label.

Loading. The page loads only the relations its columns declare: a relation column declares its own, and a ComputedColumn declares one with include. A ComputedColumn reading one it does not declare finds it unloaded. A page of the app’s own renders a Detail the same way, with Detail::load and render.

Title. record_title names the text column that titles each record, here and wherever another resource points at it: each option of a relationship choice over the resource, and each cell of a RelationColumn::of it. A title built from several columns is a column the model stores; ResourceDef::record_title has the fallback and the rules:

#![allow(unused)]
fn main() {
            .record_title(lens!(Post.title))
}

Public link. public_link adds a link to the record’s public page to the header of its detail and edit pages, for each record it returns one for: the URL to link and the text to show.

#![allow(unused)]
fn main() {
            .public_link(|_cx: &Cx, post: &Post| {
                (post.status == PostStatus::Published)
                    .then(|| PublicLink::new(format!("/blog/{}", post.id), "View on the blog"))
            })
}

Record pages

A page of the app’s own about one record, such as an order’s history or a post’s search preview, is a RecordPage of the resource. The panel serves it at {list}/{key}/{slug} and loads the record the way the detail page does, through the resource’s query and policy and the request’s tenant. The page renders only its body, under the record’s heading:

#![allow(unused)]
fn main() {
/// How a search engine lists the post: `/admin/posts/{id}/search-preview`.
pub struct SearchPreviewPage;

impl RecordPage<PostResource> for SearchPreviewPage {
    fn declare() -> RecordPageDef<Post> {
        RecordPageDef::new().icon(tablo::ui::icons::SEARCH)
    }

    async fn render(cx: &Cx, post: Post) -> Result<impl View> {
        Ok(view! {
            <p class="text-lg text-primary">(post.seo.title)</p>
            <p class="text-sm text-muted-foreground">(post.seo.description)</p>
        })
    }
}
}

ResourceDef::record_page adds it to the resource, and the record’s navigation links it:

#![allow(unused)]
fn main() {
impl Resource for PostResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .record_page::<SearchPreviewPage>()
    }
}
}

RecordPageDef::access narrows who may open the page for a record, beyond those the policy lets view it. url::record_page builds a page’s URL for a record. The panel masks nothing the page renders: a page showing a field that field_access restricts asks can_view_field first. RecordPage has the checks a request passes and what render receives.

ResourceDef::relation adds a related resource whose rows belong to a record. Each renders on the record’s detail and edit pages as that resource’s own list table, narrowed to the record:

#![allow(unused)]
fn main() {
impl Resource for PostResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            // The related model's foreign key, which holds the post's primary key.
            .relation(Relation::has_many::<CommentResource>(lens!(
                Comment.post_id
            )))
    }
}
}

The table is CommentResource’s own list table, its columns, search, sort, filters and pager included, narrowed to the post: the related resource keeps its policy, its actions and its create button, which opens with the post preselected. The panel must register the related resource too. Relation lists what the table carries, where its writes land, and how several tables share one page.

Relation tabs

A record with several related tables makes a long page, and its detail page loads every one. .tab() moves a relation’s table to a page of its own, at {list}/{key}/{related slug}: Relation::has_many::<CommentResource>(lens!(Comment.post_id)).tab() serves the post’s comments at /admin/posts/{id}/comments, and no longer under its detail and edit pages.

A resource with a tab or a record page gives its records a navigation: a tab bar under the header of the detail page, the edit page, each record page and each relation tab, linking those the request may open, the current one marked. The table on a tab is the one the detail page would show, with the same writes, landing back on the tab. Relation::tab has the checks and the mount refusals.

Many-to-many relations

Relation::belongs_to_many names the owner’s #[has_many(via = ..)] field over a join model, declared as for a many-to-many field. The table lists the related records the owner links, and attaches and detaches them as join rows:

#![allow(unused)]
fn main() {
impl Resource for TagResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            // The tag's `via` field: its articles, which its page attaches and detaches.
            .relation(Relation::belongs_to_many::<ArticleResource>(
                Tag::fields().articles(),
            ))
    }
}
}

The section’s header carries Attach, and each row and the bulk bar carry Detach, which deletes the join rows and leaves the records. Both ask the owner’s policy for Update, since linking a record edits the owner. The rows keep the related resource’s View, Edit and Delete, but no custom action and no create button: a record created there would link nothing. Relation::belongs_to_many has the routes, the hooks and the mount checks.

Relations through other relations

A customer’s payments belong to its orders, not to the customer. Toasty reaches them with a #[has_many(via = orders.payments)] field on Customer, and Relation::through::<PaymentResource>(Customer::fields().payments()) lists them on the customer’s page. The table is PaymentResource’s own, with its policy and actions, and it offers no create button and no Attach: no column of a payment holds the customer, so the table only reads. Relation::through has the rules.

One child per record

A record’s one child, such as a user’s profile, takes no table. Relation::has_one::<ProfileResource>(lens!(Profile.user_id)) renders ProfileResource’s own form inside the user’s create and edit form instead, and the save writes both in one transaction. The profile goes through its own resource: its policy, field access, rules and hooks apply as on its own pages, and the user’s key fills its foreign key. Relation::has_one has the rules and the mount checks.

Actions

An action is a mutation beyond create, update and delete. A record action runs on records: a button on each row, in the header of a record’s detail and edit pages, or an entry in the bulk bar for the selection. A header action runs on no record: a button in the header of a resource’s list or of a custom page.

Record actions

A record action is a type implementing Action<R>, added to the def with ResourceDef::action. Its NAME is its URL segment and the name policies answer for, run holds the write, and declare returns an ActionDef with everything else, each setting defaulted, as a resource’s declare returns its ResourceDef:

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

impl Action<PostResource> for Publish {
    type Input = ();
    const NAME: &'static str = "publish";

    fn declare() -> ActionDef<PostResource> {
        ActionDef::new().can_run(|_cx, post: &Post| post.status != PostStatus::Published)
    }

    async fn run(
        _cx: &Cx,
        posts: &[Post],
        _: (),
        ex: &mut dyn toasty::Executor,
    ) -> Result<tablo::Outcome, tablo::WriteError<()>> {
        Post::filter(filter_keys(posts))
            .update()
            .status(PostStatus::Published)
            .exec(ex)
            .await?;
        Ok(tablo::Outcome::done())
    }
}

impl Resource for PostResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .action::<Publish>()
            .action::<ChangeStatus>()
            .header_action::<PublishDrafts>()
    }
}
}

run holds only the write. filter_keys(posts) selects the records it receives, so one statement publishes the whole selection. The framework owns everything around it, as it does for a delete: the route and its CSRF check, the transaction the records load in and run writes through, the policy checks on every record, the hooks, and the success notification. The Action page lists each step, and what a refused record or selection answers.

Where it shows

ActionDef::places says where the button renders: each row, the detail and edit pages’ headers, the bulk bar, or any combination of them, by default all four. An action for the detail page and the bulk bar only declares:

#![allow(unused)]
fn main() {
    fn declare() -> ActionDef<PostResource> {
        ActionDef::new()
            // On the detail page and the bulk bar, not on each row or the edit page.
            .places(Places::DETAIL.with(Places::BULK))
            .label("Change status")
    }
}

Places names each place, and ActionDef::places says which routes serve an action and which places no page renders. A run from a record’s page lands back on it, so an action that hides the record from the list, such as an archive, belongs on rows and the bulk bar.

A bulk action runs on the rows checked. On a list whose rows span pages, the bulk bar also offers Select all matching, which runs it on every record the list’s search and filters select, up to Limits::bulk_records.

Who runs it

One question decides, Run on the record, and two parties answer it:

  • the policy, which each panel mounts its own, says who may run the action: RunAny { action: NAME } for the resource at all, then Run for a given record;
  • the def’s can_run says what the action itself takes, on every panel: a published post refuses “publish”.

The button, the route and can::<R>(cx, Ability::Run { .. }) in your own code all ask both, so they agree.

A record can_run refuses hides the button, unless disabled_reason says why: the button then shows disabled, with the reason on hover. A record the policy refuses never shows it, so the reason never tells a user what the policy refuses them.

Put who may act in the policy: a rule in can_run holds on every panel and no panel can lift it. A panel that mounts the resource with ReadOnly offers none of its actions and refuses their POSTs (Policy).

What a run returns

run returns an Outcome, which says what the response does once the write commits. Outcome::done() keeps the defaults: the success notification, landing back where the action ran from. A “duplicate” action reports its own message and opens the copy it made:

#![allow(unused)]
fn main() {
let outcome = Outcome::done().notify(Notification::success(format!("Duplicated {}", post.title)));
Ok(match tablo::url::edit::<PostResource>(cx, &copy) {
    Some(edit) => outcome.redirect(edit),
    None => outcome,
})
}

A file to download is a redirect to an app route that serves it.

A destructive action’s def calls confirm() to ask first through the delete’s confirmation dialog, or confirmation(question) to word its question too. icon puts an icon before the button’s label wherever it renders, and color(Color::Danger) tints the button as Delete’s is. label replaces the text derived from NAME, and label_for and icon_for change them on one record, such as “Deactivate” on an active account and “Activate” on another. A header action’s HeaderActionDef declares the same, without the per-record closures.

Header actions

A header action acts on no record: “publish every draft”, “recount the tags”, “clear the cache”. It is a type implementing HeaderAction:

#![allow(unused)]
fn main() {
/// Publishes every draft, from the post list's header.
pub(crate) struct PublishDrafts;

impl HeaderAction for PublishDrafts {
    type Input = ();
    const NAME: &'static str = "publish-drafts";

    fn declare() -> HeaderActionDef {
        HeaderActionDef::new()
            .confirm()
            // A page has no policy: the action asks the post resource's own, wherever it is
            // declared.
            .can_run(|cx| can::<PostResource>(cx, Ability::RunHeader { action: Self::NAME }))
    }

    async fn run(
        cx: &Cx,
        _: (),
        ex: &mut dyn toasty::Executor,
    ) -> Result<tablo::Outcome, tablo::WriteError<()>> {
        // No record is loaded: the action scopes its own query to the request's tenant.
        let drafts = scoped_query::<PostResource>(cx)?
            .filter(Post::fields().status().eq(PostStatus::Draft))
            .exec(&mut *ex)
            .await?;
        // The tenant's drafts are unbounded: one statement per chunk keeps each one bounded.
        for chunk in drafts.chunks(500) {
            Post::filter(filter_keys(chunk))
                .update()
                .status(PostStatus::Published)
                .exec(&mut *ex)
                .await?;
        }
        Ok(tablo::Outcome::done())
    }
}
}

ResourceDef::header_action::<A>() puts its button in the header of the resource’s list, as the post resource above does with PublishDrafts. The policy decides who runs it through ViewAny, since the button is on the list, and RunHeader, which ability.is_header_action::<PublishDrafts>() matches. It is an ability of its own because a policy that grants every record action and checks Run per record must not grant a header action by accident: no record is there to check.

For the same reason, nothing scopes a header action to the request’s tenant: an action over a tenant’s records reads them through scoped_query, as PublishDrafts does.

A page declares its header actions with PageDef::header_action::<A>(). The default render shows their buttons in the page’s header; a page that writes its own places them with header_action_buttons::<Self>(cx):

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

impl Page for MaintenancePage {
    fn declare() -> PageDef {
        PageDef::new().header_action::<PublishDrafts>()
    }
}
}

An action whose button belongs in the page’s content, such as a plan card’s Subscribe that posts the plan it offers, is declared with PageDef::action::<A>() instead: the page serves its route and leaves it out of the header, and the page or one of its widgets places its button with header_action_button::<Page, A>(cx, &input).

A page has no policy: its header actions run for whoever may open it. An action that writes a resource’s records asks that resource’s policy in its own can_run, as PublishDrafts does, so it runs for the same users from the list and from the page.

Asking for input

An action names what it asks for before it runs as type Input: () for nothing, or a struct deriving FormInput, which run receives parsed. A record action and a header action ask the same way:

#![allow(unused)]
fn main() {
/// What changing a post's status asks for.
#[derive(FormInput)]
pub(crate) struct StatusChange {
    #[form(options)]
    pub status: PostStatus,
    #[form(label = "Feature on the home page")]
    pub featured: bool,
}

pub(crate) struct ChangeStatus;

impl Action<PostResource> for ChangeStatus {
    type Input = StatusChange;
    const NAME: &'static str = "change-status";

    fn declare() -> ActionDef<PostResource> {
        ActionDef::new()
            // On the detail page and the bulk bar, not on each row or the edit page.
            .places(Places::DETAIL.with(Places::BULK))
            .label("Change status")
    }

    fn validate_input(_cx: &Cx, change: &StatusChange) -> FieldErrors<StatusChange> {
        let mut errors = FieldErrors::<StatusChange>::new();
        if change.featured && change.status == PostStatus::Draft {
            errors.add(|f| f.featured, "Only a published post is featured");
        }
        errors
    }

    async fn run(
        _cx: &Cx,
        posts: &[Post],
        change: StatusChange,
        ex: &mut dyn toasty::Executor,
    ) -> Result<tablo::Outcome, tablo::WriteError<StatusChange>> {
        Post::filter(filter_keys(posts))
            .update()
            .status(change.status)
            .featured(change.featured)
            .exec(ex)
            .await?;
        Ok(tablo::Outcome::done())
    }
}
}

Its button opens the input’s form in a dialog over the page instead of running. The derive picks each field’s control and its required mark as a record form does; FormInput lists its field attributes and the names an input may not use.

A dialog that runs the action two ways, such as Ship and Ship and notify, keeps one action and gives its input a bool field the second button checks: fn submits(submits: Submits<Shipping>) -> Submits<Shipping> { submits.add("Ship and notify", |f| f.notify) }. The dialog renders no checkbox for notify, so the action’s own button posts it false and the second button true, and run reads which one ran it. Both go through the same route and checks; Submits has the rules.

A refusal lands on the input, never on a half-written record. validate_input refuses before the transaction opens and sees no record, as ChangeStatus refuses to feature a draft. Its errors are keyed by the input, FieldErrors::<StatusChange>::new(), and each picks the field it refuses by name, errors.add(|f| f.featured, ".."), so a renamed field fails to compile rather than render no message. A rule that reads the database refuses from run with Err(WriteError::<StatusChange>::field(|f| f.featured, "..")), keyed by the input too, and the transaction rolls back what run wrote. Either way the input renders as a page with the error under its control. A reason that names no field declines instead, with Err(WriteError::declined("..")): the transaction rolls back and the message flashes.

Names

An action’s NAME is its URL segment. A name that is not one segment does not compile, and mounting the panel refuses a name two actions of one resource, or two header actions of one page, share.

Notifications

A Notification is a status, a title, an optional description and optional links. An action flashes one as a toast after its write. Sent with Notifications, the same value is stored for one panel user and listed in the bell of a panel that shows one.

The bell

Panel::notifications shows a bell at the end of the topbar:

#![allow(unused)]
fn main() {
    Panel::new("admin").notifications()
}

The bell counts the signed-in user’s unread notifications and opens a sheet that lists them, newest first, with their links. Once the page loads, it keeps updating over Topcoat’s runtime connection, so a notification sent while the page is open shows at once, as a toast. The panel needs auth and the StoredNotification model, which tablo::models! registers. Panel::notifications has the rules.

Sending

In a request, Notifications::of(cx) sends on the request’s panel, for the tenant the request acts for. send takes the recipient’s PanelUser::user_id:

#![allow(unused)]
fn main() {
    Notifications::of(cx)?
        .send(
            owner_id,
            Notification::success("Your export is ready")
                .description("It holds every order of the quarter.")
                .action("Download", format!("/exports/{export}.csv")),
        )
        .await?;
}

send writes the row on its own connection and commits it at once. Inside a write’s transaction, in a record fn, an action’s run or Resource::before_commit, send through the transaction instead, so the notification commits with the write or not at all; Notifications::send_in has the rules:

#![allow(unused)]
fn main() {
    Notifications::of(cx)?
        .send_in(ex, owner_id, Notification::success("Your order shipped"))
        .await?;
}

A job sends through the panel’s handle, for no tenant until tenant names one:

#![allow(unused)]
fn main() {
    admin
        .notifications()
        .tenant(tenant)
        .send(owner_id, Notification::info("The nightly import finished"))
        .await?;
}

Who sees what

The bell lists a user’s notifications on its own panel: those sent for the tenant they act for, and those sent for no tenant. A notification for one tenant therefore never shows to a member of another, and one sent for no tenant, such as a job’s, shows whichever tenant the user acts for.

Keeping them

Nothing deletes stored notifications on its own. A job prunes the ones older than the app keeps:

#![allow(unused)]
fn main() {
    admin
        .notifications()
        .prune(Duration::from_hours(24 * 90))
        .await?;
}

One process

A send wakes only the bells open on the process that sent it: behind a load balancer, a bell on another process shows the notification on its next page load.

Translations

A panel renders its words in the request’s locale. Tablo ships English and French catalogs, and an app adds its own in Fluent, the format a message picks its plural and gender forms in.

Offering locales

Panel::locales lists the locales a panel offers, the default first, and Panel::translations adds the app’s catalog for one. A locale is a topcoat::l10n::Locale, which locale! checks at compile time; enable the l10n feature of the app’s topcoat dependency to name it:

    Panel::new("admin")
        .locales([locale!("fr"), locale!("en")])
        .translations(locale!("fr"), include_str!("../locales/fr.ftl"))
        .translations(locale!("en"), include_str!("../locales/en.ftl"))

A panel that lists none offers English alone. A request reads, in order:

  1. the locale the visitor picked from the shell’s language menu;
  2. the signed-in user’s PanelUser::locale, when the panel offers a match;
  3. the best match of the browser’s Accept-Language, by weight, without a language it weighs q=0;
  4. the panel’s default, the first it lists.

The language menu

A panel offering several locales shows them in the sidebar footer, beside the theme: picking one posts to {prefix}/locale and lands back on the page it was picked from, and a cookie under the panel’s prefix remembers it for a year, so two panels on one host read in two languages. A panel offering one locale shows no menu and serves no post, and a locale dropped from Panel::locales since a visitor picked it reads as none.

Each locale is named by an attribute of the message tablo-shell-language, which Tablo’s catalogs spell for English and French; a panel offering another locale names it in its own catalog, and one no catalog names reads as its tag:

tablo-shell-language =
    .de = Deutsch

A region reads its language’s locale: fr-CA reads a panel’s fr, and zh-HK reads zh-Hant over zh-Hans. The page’s <html lang> names the locale it was read in, its <html dir> the direction the locale’s script runs in, rtl for Arabic or Hebrew, and a panel offering several locales answers Vary: Accept-Language, Cookie, so a shared cache keeps one copy per language. A page, a handler or a view of the panel reads the request’s locale with topcoat::l10n::locale(cx).

The panel refuses to mount an empty list, a locale listed twice (iw and he name one), a locale no catalog translates, a catalog for a locale the panel does not offer (en aside), and a catalog that is not valid Fluent, each as a LocaleFault under DeclarationErrorKind::Locale (Mount errors).

Catalogs

A catalog holds the app’s messages, and any of Tablo’s it spells otherwise:

resource-post = Article
    .plural = Articles
field-title = Titre
posts-published = { $count ->
    [one] { $count } article publié
   *[other] { $count } articles publiés
}
tablo-shell-sign-out = Quitter

A message the request’s locale leaves out reads from the default locale’s catalogs, then from English, so a partial translation renders, and so does an attribute a message redefines without. An English locale reads English alone. Tablo’s message ids start with tablo-, so an app’s other ids never collide with them; its locales/en.ftl lists every one, and an app overrides one by defining its id.

A catalog calls Fluent’s NUMBER function, such as { NUMBER($total, minimumFractionDigits: 2) }. Numbers render without grouping in every locale.

Labels

Every label a declaration takes is a Text: a string renders as written, and text! names a message, with its arguments:

    Post::columns().title.text().label(text!("post-headline"))

A label Tablo derives from a name is a message whose fallback is the derived English, so an app translates it in its catalog without declaring it:

DeclaredMessageFallback
a field, column or filter on word_countfield-word_countWord count
one on the foreign key author_id of the belongs_to relation author, or on the relationfield-authorAuthor
a resource over the model BlogPostresource-blog-postBlog post
its pluralresource-blog-post.pluralBlog posts
the plural of a label text!("post")post.pluralthe id
a page ReportsPagepage-reportsReports
an action named publish-draftsaction-publish-draftsPublish drafts
the variant PublishedLate of an Options enum PostStatusoption-post-status.published_latePublished late

A field, its column and its filter share the message of their name, so one translation spells all three. A belongs_to relation’s one foreign key shares the relation’s message: the relationship field on author_id and the relation column on author read the same label. An enum’s options are the attributes of one message, which spells the enum’s select, its column’s cells, its group headers and its filter’s options:

option-post-status =
    .draft = Brouillon
    .published_late = Publié en retard

An embedded enum’s variant reads the same message. #[option(label = "..")] declares a plain label, and a choice’s options takes (value, label) pairs whose label is a Text, so [("draft", text!("status-draft"))] translates too. A plain label’s plural is the label pluralized in English: one written in another language wants its plural_label declared.

Words outside a label

t! spells a message in the request’s locale where a String is wanted, such as a notification’s title, which is stored as sent:

    Notification::success(t!(cx, "posts-published", count = count))

A Text also renders in a view! as it is, read in the view’s locale. The auth mails, a reset link, a verification link and a sign-in code, are written in their recipient’s PanelUser::locale, else in the locale of the request that sends them.

Numbers and amounts

A .numeric(..) or .money(..) column, a chart and a stat spell numbers with three messages of the request’s catalog: tablo-number-group, the thousands separator, tablo-number-decimal, the decimal mark, and tablo-money, which places the sign, the symbol and the amount. English reads -$1,234.50, French -1 234,50 $. A catalog for another locale spells its own:

tablo-number-group = .
tablo-number-decimal = ,
tablo-money = { $sign }{ $amount }{ "\u00A0" }{ $symbol }

Fluent trims a message’s outer spaces, so a space separator is a quoted literal: { "\u202F" }. A currency whose symbol keeps one side in every locale says so with Currency::symbol_before() or Currency::symbol_after().

The user’s locale

PanelUser::locale names the locale a user reads the panel in, such as one they pick on their profile and the app stores as text. A locale with no match among the panel’s counts as none, and one the user picks from the language menu outranks it for the rest of their visits, though their mails still read the stored one:

pub struct Editor {
    pub id: String,
    pub locale: Option<String>,
}

impl tablo::PanelUser for Editor {
    fn user_id(&self) -> String {
        self.id.clone()
    }

    fn display_name(&self) -> &str {
        &self.id
    }

    fn can_access_panel(&self, _panel: &tablo::PanelId) -> bool {
        true
    }

    fn locale(&self) -> Option<Locale> {
        self.locale.as_deref()?.parse().ok()
    }
}

Finding untranslated words

Offer the pseudo-locale en-XA to see which words no catalog spells: it renders every catalog message with accented letters, so a word that reads plain is one written as a plain string.

What an operator reads, a mount error or a log line, stays English. So do the few words of the UI primitives Tablo copies from upstream (“More”, “More pages”, “Sidebar”, “Toggle sidebar”).

Policy, auth, tenancy

Three layers decide what a request may do. Authentication decides who is signed in. Tenancy limits a signed-in user to the rows of the tenant they act for. Policy — the resource’s ResourceDef::policy — decides what that user may do with each resource and record.

Policy

A policy answers one Ability at a time. The default policy is Deny, so a new resource exposes nothing until you allow it. Abilities declares who may do what, one ability per method, and refuses every ability it does not declare:

#![allow(unused)]
fn main() {
use tablo::prelude::*;

impl Resource for UserResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .policy(
                Abilities::<User>::new()
                    .view_any(|_cx| true)
                    .view(|_cx, _user| true)
                    .create(is_admin)
                    .update(|_cx, user| !user.sso_managed)
                    .delete(|cx, _user| is_admin(cx)),
                // No restore or action: each is refused until the policy declares it.
            )
    }
}
}

Each Ability variant names one thing a user may do: list, view, create, update, delete, restore, run an action. Its page says which pages and POSTs ask it.

A closure policy matches the variants itself. RunAny and Run carry action, the action’s NAME, so one policy tells a resource’s actions apart. ability.is_action::<Publish, _>() asks whether the ability is RunAny or Run for the action type Publish, so renaming the action’s NAME cannot leave a policy matching the old string:

#![allow(unused)]
fn main() {
pub fn post_policy(cx: &Cx, ability: Ability<'_, Post>) -> bool {
    match ability {
        Ability::ViewAny | Ability::View(_) => true,
        // `Publish` is the action's type, so renaming its `NAME` keeps this arm matching.
        _ if ability.is_action::<Publish, _>() => editors_only(cx),
        _ => false,
    }
}
}

The _ is the resource, inferred when the action belongs to one. A header action, which runs on no record, is asked RunHeader, which ability.is_header_action::<A>() matches.

Three rules shape every policy; Policy lists the rest:

  • Handlers ask what buttons ask. A hidden button is also a refused request, answered 403.
  • Reading rows asks ViewAny only. The list, the export, related tables and relationship choices show every row of the resource’s query. A policy is Rust code that cannot run in the database, and filtering rows after the query would leave pages short and counts wrong. Rows a user must not see belong out of ResourceDef::query; see Resources. View decides who opens a record: a list row it refuses shows without its actions.
  • Writes are checked against the stored row, loaded inside the write’s transaction, never against the submitted key.

The policy sees the row as stored, never what the submission writes over it. Who may change a field at all is field access: its edit rule disables the control and keeps the stored value. A rule about the values a write stores, such as who may set a post to published, belongs in Resource::before_commit, which receives the Change inside the write’s transaction: a Change::Create with the new row, a Change::Update with before and after, and a custom action’s Change::Action with each row’s before and after, so the same rule covers an action that publishes. before_commit’s Err rolls the write back:

#![allow(unused)]
fn main() {
/// Refuses a write that publishes a post unless an editor makes it. Called from
/// `PostResource::before_commit`, it sees what the write stores, which the policy does not.
pub async fn only_editors_publish(cx: &Cx, change: &tablo::Change<Post>) -> Result<()> {
    let published = |post: &Post| matches!(post.status, PostStatus::Published);
    let publishes = match change {
        tablo::Change::Create(post) => published(post),
        tablo::Change::Update { before, after } => !published(before) && published(after),
        tablo::Change::Action { records, .. } => records
            .iter()
            .any(|acted| !published(&acted.before) && acted.after.as_ref().is_some_and(published)),
        _ => false,
    };
    if publishes && !editors_only(cx) {
        return Err(topcoat::router::error::forbidden().into());
    }
    Ok(())
}
}

Building a policy

Allow, Deny, ReadOnly (ViewAny and View, no Export) and when(predicate) are policies, and each combines with another through and and or. when allows every ability while a predicate on the request holds, which suits a rule about the user or the tenant that several resources share. The rule reads the app’s own user type, Staff here (see Your own user table):

#![allow(unused)]
fn main() {
pub fn editors_only(cx: &Cx) -> bool {
    tablo::auth::user::<Staff>(cx).is_some_and(|staff| staff.editor)
}

impl Resource for PostResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .policy(ReadOnly.or(when(editors_only)))
    }
}

impl Resource for AuthorResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .policy(when(editors_only))
    }
}
}

A closure ending in _ => true allows every ability it does not name: the restore a soft delete adds, an action declared later, any ability a later Tablo release adds. Prefer Abilities, which refuses those, or name every variant so that a new one fails to compile. Abilities declares an action’s check with run::<A, _>:

#![allow(unused)]
fn main() {
pub fn post_abilities() -> Abilities<Post> {
    Abilities::<Post>::new()
        .view_any(|_cx| true)
        .view(|_cx, _post| true)
        .create(editors_only)
        .update(|cx, post| editors_only(cx) && post.status != PostStatus::Published)
        .run::<Publish, _>(|cx, _post| editors_only(cx))
    // No delete: `DeleteAny` and `Delete` are refused, and so is any action added later.
}
}

A write’s record check also allows the write at all, and view does not allow ViewAny: Abilities has the rules for each method. A header action is declared with run_header::<A>.

A policy that allows everything but some writes reads ability.written_record(), the record an update, delete, restore, force delete or record action’s run writes, so a record action the resource gains later is refused too. Create and RunHeader write no record they are handed and answer None; a policy that must refuse them matches them by name:

#![allow(unused)]
fn main() {
pub fn unfeatured_only(_cx: &Cx, ability: Ability<'_, Post>) -> bool {
    // Refuses an update, a delete, a restore, a force delete or a record action's run on a
    // featured post, and allows every other ability: a create or a header action writes no
    // existing record, so a policy that refuses those matches them by name.
    ability.written_record().is_none_or(|post| !post.featured)
}
}

policy takes any type that implements Policy<M>, Abilities among them, and policy_fn takes a closure |cx, ability| -> bool. Within declare, the def learns its resource from the return type only after the closure is checked, so a closure that reads the record names the ability’s type, ability: Ability<'_, User>, or the chain starts from ResourceDef::<Self>::new().

Loading what a policy reads

A policy is asked once per row and once per button, so it does not await: it reads the request. What it needs beyond the signed-in user, such as a plan’s limit or a count, the panel loads once for the request with Panel::load, and loaded::<T>(cx) reads it back:

#![allow(unused)]
fn main() {
/// How many posts the request's workspace holds, counted once for the request.
pub struct PostCount(pub usize);

impl tablo::Load for PostCount {
    async fn load(cx: &Cx) -> Result<Self> {
        let Some(workspace) = tablo::tenant_id(cx) else {
            return Ok(Self(0));
        };
        let mut db = tablo::db::db(cx)?;
        let posts = Post::filter(Post::fields().tenant_id().eq(workspace))
            .exec(&mut db)
            .await?;
        Ok(Self(posts.len()))
    }
}

/// Offers Create while the workspace holds fewer than ten posts.
pub fn under_quota(cx: &Cx) -> bool {
    tablo::loaded::<PostCount>(cx).is_some_and(|count| count.0 < 10)
}

pub fn quota_panel() -> Panel {
    Panel::new("admin").load::<PostCount>()
}
}

load runs after the auth gate admitted the request, so it reads the user and the tenant the request acts for. It runs on every request the panel answers, the runtime requests of its pages included: keep it to one or two statements. loaded answers None on a panel that does not load the type and on a signed-out page, which a policy reads as a refusal. A query_fn, a when predicate and a column’s or an action’s condition read it the same way.

A policy hides the button; a limit that must hold under two concurrent writes is checked again in Resource::create_record or before_commit, inside the write’s transaction.

In your own code

can::<R>(cx, ability) asks R’s policy, for a page or route that renders or writes R’s records itself. can_list::<R>(cx) answers whether the request may open R’s list: the panel’s sign-in, R’s tenant, and ViewAny, the checks the list handler makes. A dashboard that links to lists checks it before rendering each link.

A page, route or shard the app serves under a panel calls auth::guard(cx)? to require the panel’s signed-in user exactly as the panel’s own pages do. A shard needs it: Topcoat serves shards at its runtime path, where the page’s checks do not run. The panel declares the shards and procedures its pages use with Panel::endpoint, so they run as that panel.

A form route verifies the CSRF token it posted under csrf::FIELD_NAME with csrf::verify(cx, token).

Authentication

Authentication is on by default. The built-in login checks an email and password against the AdminUser table and keeps sessions in the AuthSession table. tablo::models! registers both beside the app’s models; create a user with auth::create_admin, which stores the password’s hash:

#![allow(unused)]
fn main() {
pub fn auth_models() {
    // `Book`, beside `AdminUser`, `AuthSession`, `ColumnPreference`, `AuthToken` and `AuthFactor`.
    let _ = tablo::models!(crate::Book);
}
}

A panel whose lists declare toggleable columns also keeps each user’s choice in the ColumnPreference table. A feature that mails links, such as a password reset, keeps its tokens in AuthToken, and two-factor sign-in its factors in AuthFactor; tablo::models! registers all three. An app listing its models with toasty::models! lists these too, and the mount names any it misses. Toasty names a table after its model, so an app with a model named as one of Tablo’s, such as its own AdminUser, lists its models that way.

#![allow(unused)]
fn main() {
pub async fn seed_admin(mut db: toasty::Db) -> Result<()> {
    // Stores the password's Argon2id hash, never the plaintext.
    tablo::auth::create_admin(&mut db, "admin@example.com", "secret", "Admin").await?;
    Ok(())
}

/// Your own user table hashes with the same function.
pub async fn staff_hash() -> Result<String> {
    tablo::auth::hash_password("secret").await
}
}

Your first panel shows the complete setup.

What a request gets

RequestSigned in with panel accessSigned in without panel accessNot signed in
GET of a panel pagethe page, or its error page403 page with Sign outredirect to /admin/login?next=…
any other panel requesthandled403401
/_topcoat/runtimehandled403401

After login, the user returns to next, which must be a same-origin path. A user has panel access when their AdminUser.active is true. The gate covers only the panel prefix and /_topcoat/runtime; routes elsewhere, including your app’s own routes and directories served with Panel::serve_dir, are public — a directory served under the panel prefix is the exception, since the gate covers the prefix. Panel::uploads_dir answers only at the signed URLs the panel’s pages render. On a router with several panels, /_topcoat/runtime answers 401 without a session only when every panel is gated.

  • Login verifies Argon2id hashes and treats an email’s case as insignificant; each login may make five attempts a minute from one address, which Auth::throttle changes; Auth::account_throttle adds an opt-in limit per login across addresses (Security). PasswordAuth has the details, and what to do about rows stored with capitals.
  • Sessions are rows in AuthSession, valid for seven days, and each belongs to the panel that signed the user in: a user signed in to /admin is anonymous on /portal. A back office usually wants less: Auth::sessions(Sessions::new().lifetime(..).idle_timeout(..)) shortens the lifetime and ends a session nobody uses (Sessions). AuthSession has the rules and the columns it needs.
  • Revoking. Call auth::revoke_sessions_for_user(cx, user_id) when a user’s password changes or their account is deactivated; otherwise existing sessions stay valid until they expire.

Read the signed-in user in your own code as your user type: auth::user::<AdminUser>(cx) returns Option<&AdminUser>, and auth::require_user::<AdminUser>(cx)? answers the request as the table above when nobody is signed in. auth::signed_in(cx) answers whether anyone is.

Your own user table

A table that signs in by email and password needs no seam of its own. Implement PasswordAccount for the model: four lenses name its name, email, password hash and verification time, and sign_in turns a row into the user the panel signs in, here the member with their workspaces:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, toasty::Model)]
pub struct Member {
    #[key]
    #[auto]
    pub id: uuid::Uuid,
    pub name: String,
    #[unique]
    pub email: String, // stored lowercase
    pub password_hash: String,
    pub email_verified_at: Option<jiff::Timestamp>,
    pub active: bool,
}

pub struct SignedMember {
    pub member: Member,
    pub workspaces: Vec<Membership>,
}

impl PanelUser for SignedMember {
    fn user_id(&self) -> String {
        self.member.id.to_string() // the key, as its `Display` spells it
    }
    fn display_name(&self) -> &str {
        &self.member.name
    }
    fn email(&self) -> Option<&str> {
        Some(&self.member.email)
    }
    fn can_access_panel(&self, _panel: &tablo::PanelId) -> bool {
        true
    }
    fn tenants(&self) -> &[Membership] {
        &self.workspaces
    }
}

impl PasswordAccount for Member {
    type User = SignedMember;

    fn name() -> Lens<Self, String> {
        lens!(Member.name)
    }
    fn email() -> Lens<Self, String> {
        lens!(Member.email)
    }
    fn password_hash() -> Lens<Self, String> {
        lens!(Member.password_hash)
    }
    fn email_verified_at() -> Lens<Self, Option<jiff::Timestamp>> {
        lens!(Member.email_verified_at)
    }
    fn account(user: &SignedMember) -> &Member {
        &user.member
    }
    async fn sign_in(
        self,
        _cx: &Cx,
        ex: &mut dyn toasty::Executor,
    ) -> Result<Option<SignedMember>> {
        if !self.active {
            return Ok(None); // its login fails and its sessions end
        }
        let workspaces = member_workspaces(ex, &self).await?;
        Ok(Some(SignedMember {
            member: self,
            workspaces,
        }))
    }
}
}

PasswordAuth::<Member> is then the panel’s authenticator, and its profile editor, password resetter and email verifier too:

#![allow(unused)]
fn main() {
pub fn member_panel(mail: AuthMail) -> Panel {
    let members = PasswordAuth::<Member>::default();
    Panel::new("app").auth(
        Auth::custom(members)
            .profile(members)
            .mail(mail)
            .password_reset(PasswordReset::new(members))
            .email_verification(EmailVerification::new(members)),
    )
}
}

It signs in, edits, resets and verifies as it does for AdminUser, and stores each email trimmed and lowercased, so a sign-up that writes the table stores it as auth::normalize_email spells it. A resource’s edit form that changes a member’s email or password hash ends their sessions, as it does an admin’s. PasswordAccount lists its hooks: a profile change the app refuses, and where a picked locale is stored.

A table that signs in some other way implements PanelUser for the type the panel signs in, and Authenticator to load it:

#![allow(unused)]
fn main() {
use tablo::{Authenticator, Membership, PanelUser, auth::verify_password};

pub struct SignedStaff {
    pub staff: Staff, // your model
    pub workspaces: Vec<Membership>,
}

impl PanelUser for SignedStaff {
    fn user_id(&self) -> String {
        self.staff.id.to_string()
    }
    fn display_name(&self) -> &str {
        &self.staff.name
    }
    fn can_access_panel(&self, _panel: &tablo::PanelId) -> bool {
        self.staff.active
    }
    fn tenants(&self) -> &[Membership] {
        &self.workspaces
    }
}

pub struct StaffAuth;

impl Authenticator for StaffAuth {
    type User = SignedStaff;

    async fn verify(&self, cx: &Cx, login: &str, password: &str) -> Result<Option<SignedStaff>> {
        let staff = find_staff_by_email(cx, login).await?;
        if !verify_password(password, staff.as_ref().map(|s| s.password_hash.as_str())).await {
            return Ok(None);
        }
        // … load the memberships and return Some(SignedStaff { .. })
        todo!()
    }

    async fn find_by_id(&self, _cx: &Cx, _id: &str) -> Result<Option<SignedStaff>> {
        // … the same user and memberships, by `user_id`
        todo!()
    }
}

pub async fn find_staff_by_email(_cx: &Cx, _login: &str) -> Result<Option<Staff>> {
    todo!()
}
}
#![allow(unused)]
fn main() {
pub fn staff_auth_panel() -> Panel {
    Panel::new("admin").auth(Auth::custom(StaffAuth))
}
}
  • The user type is yours. It need not be a model: the showcase’s SignedStaff is a row plus the workspaces it holds a seat in. auth::user::<SignedStaff>(cx) reads it back, fields and all, and answers None on a panel whose authenticator loads another type.
  • verify checks credentials. Return Ok(None) for every credential failure. verify_password checks an Argon2id hash and, given None for an unknown account, does the same work, so response times do not reveal which accounts exist. It and hash_password run on Tokio’s blocking pool, so await them rather than hashing on the request’s task.
  • find_by_id reloads the user on every request, so deactivating a user or removing a membership takes effect immediately.
  • time_zone names the zone the user reads and enters times in, such as one they pick on their profile page and the app stores; it defaults to the panel’s. See Time zones.
  • locale names the locale the user reads the panel in; it defaults to the browser’s best match. See Translations.

Sessions stay in AuthSession, which tablo::models! registers. It registers the shipped AdminUser too, which only PasswordAuth::new() reads: with another authenticator its table stays empty.

An app with a sign-in of its own, such as SSO, keeps it through Auth::external: see Adding a panel to an existing app.

Sign-up

Auth::registration lets visitors create their own account at {prefix}/register, which the login page links to. PasswordSignUp registers an AdminUser from a name, an email address and a password typed twice:

#![allow(unused)]
fn main() {
pub fn open_sign_up_panel() -> Panel {
    Panel::new("admin").auth(Auth::password().registration(PasswordSignUp::pending()))
}
}

PasswordSignUp::pending stores each account inactive: the sign-up lands on the login page, and the account signs in once an administrator sets active. PasswordSignUp::open stores it active and signs it in at once, and an active AdminUser may open the whole panel, so choose it only where any visitor may hold an account.

Your own user table registers through a Registrar beside its Authenticator, which works like an action with input: Input is the form the page asks for, validate refuses a submission field by field, and register writes the account. Both run in one transaction the framework opens:

#![allow(unused)]
fn main() {
#[derive(FormInput)]
pub struct StaffSignUp {
    pub name: String,
    #[form(email)]
    pub email: String,
    #[form(password)]
    pub password: String,
    #[form(password, label = "Confirm password")]
    pub password_confirmation: String,
}

impl Registrar for StaffAuth {
    type Input = StaffSignUp;
    type User = SignedStaff;

    async fn validate(
        &self,
        _cx: &Cx,
        sign_up: &StaffSignUp,
        ex: &mut dyn toasty::Executor,
    ) -> Result<FieldErrors> {
        let mut errors = new_password_errors(&sign_up.password, &sign_up.password_confirmation);
        if email_taken(ex, &sign_up.email).await? {
            errors.add_field("email", "Email has already been taken");
        }
        Ok(errors)
    }

    async fn register(
        &self,
        _cx: &Cx,
        sign_up: StaffSignUp,
        ex: &mut dyn toasty::Executor,
    ) -> Result<SignedStaff> {
        let hash = hash_password(&sign_up.password).await?;
        let staff = create_staff(ex, &sign_up.name, &sign_up.email, &hash).await?;
        Ok(SignedStaff {
            staff,
            workspaces: Vec::new(),
        })
    }
}
}
#![allow(unused)]
fn main() {
pub fn staff_sign_up_panel() -> Panel {
    Panel::new("admin").auth(Auth::custom(StaffAuth).registration(StaffAuth))
}
}

Auth::registration lists how the form posts, where the visitor lands after the commit, what the mount refuses and how sign-ups are throttled. The sign-up page tells a visitor whether an email is taken, which the login page never does.

Profile

Auth::profile adds a profile page at {prefix}/profile, which the user menu links to, where the signed-in user edits their own account. PasswordAuth edits an AdminUser’s name, email address and password:

#![allow(unused)]
fn main() {
pub fn profile_panel() -> Panel {
    Panel::new("admin").auth(Auth::password().profile(PasswordAuth::new()))
}
}

It asks for the current password before the email or the password changes, refuses a new password new_password_errors refuses and, once the current password verifies, an email another account holds, and leaves the password as it is when the new-password field is blank.

A PasswordAccount table edits through its PasswordAuth as above. Another table edits through a ProfileEditor beside its Authenticator, which works like a Registrar: fill seeds the form from the signed-in user, validate refuses a submission field by field, and save writes it. validate and save run in one transaction the framework opens. The shipped Profile input fits any table with a name, an email and a password:

#![allow(unused)]
fn main() {
impl ProfileEditor for StaffAuth {
    type Input = Profile;
    type User = SignedStaff;

    fn fill(&self, _cx: &Cx, signed: &SignedStaff) -> Profile {
        Profile {
            name: signed.staff.name.clone(),
            email: signed.staff.email.clone(),
            password: None,
            password_confirmation: String::new(),
            current_password: None,
        }
    }

    async fn validate(
        &self,
        _cx: &Cx,
        signed: &SignedStaff,
        profile: &Profile,
        ex: &mut dyn toasty::Executor,
    ) -> Result<FieldErrors> {
        let mut errors = profile.password_errors();
        let current = profile.current_password.as_deref().unwrap_or_default();
        let credentials = profile.password.is_some() || profile.email != signed.staff.email;
        if credentials && !verify_password(current, Some(&signed.staff.password_hash)).await {
            errors.add_field("current_password", "The current password is incorrect");
        } else if profile.email != signed.staff.email && email_taken(ex, &profile.email).await? {
            // Asked only once the password verifies: a stolen session learns no addresses.
            errors.add_field("email", "Email has already been taken");
        }
        Ok(errors)
    }

    async fn save(
        &self,
        _cx: &Cx,
        signed: &SignedStaff,
        profile: Profile,
        ex: &mut dyn toasty::Executor,
    ) -> Result<ProfileUpdate> {
        let update = if profile.password.is_some() || profile.email != signed.staff.email {
            ProfileUpdate::Credentials
        } else {
            ProfileUpdate::Details
        };
        let hash = match &profile.password {
            Some(password) => Some(hash_password(password).await?),
            None => None,
        };
        update_staff(ex, &signed.staff, &profile.name, &profile.email, hash).await?;
        Ok(update)
    }
}
}

Auth::profile lists what the form renders, which saves end the user’s sessions, what the mount refuses and how saves are throttled.

Password reset

Auth::password_reset adds a “Forgot your password?” link to the login page. It leads to {prefix}/forgot-password, which mails a reset link, and the link opens {prefix}/reset-password, where the visitor chooses a new password. Auth::mail names the sender and the base URL every link the panel mails starts with. The mail goes through the router’s Mailer, so add one before mounting the panel, and add AuthToken to the Db’s models:

#![allow(unused)]
fn main() {
pub fn reset_router(db: toasty::Db) -> Result<Router> {
    let auth = Auth::password()
        .mail(AuthMail::new(
            Mailbox::named("Example", "no-reply@example.com")?,
            "https://admin.example.com",
        ))
        .password_reset(PasswordReset::new(PasswordAuth::new()));
    let mut builder = Router::builder()
        .with(db)
        // Before the panel, which checks for it. `SmtpTransport`, behind Topcoat's `mail-smtp`
        // feature, delivers in production; `FileTransport` writes `.eml` files instead.
        .with(Mailer::new(FileTransport::new("target/mail")));
    builder.panel(Panel::new("admin").auth(auth))?;
    Ok(builder.build())
}
}

The base URL is the scheme and host the app answers on. Reset links start with it rather than with the request’s Host header, which the client chooses and could point at another host.

Another user table than a PasswordAccount resets through a PasswordResetter beside its Authenticator: find_by_email loads the account an address signs in as, and reset_password sets the new password inside the reset’s transaction. The link goes to the address PanelUser::email answers; an account that answers none gets no link.

Auth::password_reset lists how long a link works, what a reset ends, what the mount refuses and how requests are throttled. The request page answers the same whether an account uses the address or not, so it never reveals one.

Email verification

Auth::email_verification makes every signed-in user prove they read the address PanelUser::email answers before the panel serves them anything else. It mails links through Auth::mail, like a password reset:

#![allow(unused)]
fn main() {
pub fn verified_auth() -> Result<Auth> {
    Ok(Auth::password()
        .mail(AuthMail::new(
            Mailbox::named("Example", "no-reply@example.com")?,
            "https://admin.example.com",
        ))
        .registration(PasswordSignUp::open())
        .email_verification(EmailVerification::new(PasswordAuth::new())))
}
}

Another user table than a PasswordAccount verifies through an EmailVerifier beside its Authenticator: is_verified says whether the user has proved their address, and store_verified_email stores the address a link proved and marks it verified, inside the link’s transaction. PasswordAuth keeps the proof in the account’s email_verified_at column; create_admin seeds a verified AdminUser.

Accounts that predate verification are unverified, seeded admins included: backfill email_verified_at for the addresses you already trust before turning it on. A new email waits for its own link: a profile editor calls auth::request_email_change from save instead of writing the address, as PasswordAuth does. Auth::email_verification lists what each link does and for how long, what the mount refuses and how links are throttled.

Two-factor sign-in

Auth::two_factor lets each signed-in user add an authenticator app, and asks an account that has one for a code from it after its password. The panel stores the factors itself, as AuthFactor rows, so it works with any Authenticator. Each authenticator secret is sealed under the router’s cookie Key, which the router must hold:

#![allow(unused)]
fn main() {
pub fn two_factor_router(db: toasty::Db, cookie_key: &[u8]) -> Result<Router> {
    let auth = Auth::password().two_factor(TwoFactor::new());
    let mut builder = Router::builder()
        .with(db)
        // Seals each authenticator secret. Load the same 64 random bytes or more at every start,
        // kept with the app's other secrets: a new key opens no secret sealed under the old one.
        .with(Key::from(cookie_key));
    builder.panel(Panel::new("admin").auth(auth))?;
    Ok(builder.build())
}
}

Add AuthFactor and AuthToken to the Db’s models.

Panels that load the same user type share an account’s factor: set up on one, it is asked on each that installs Auth::two_factor, and turning it off on one turns it off on all. The cookie Key seals the secrets, so rotating it makes every app code fail until its owner signs in with a recovery code. Auth::two_factor lists the setup, the challenge, codes by email, throttling and what the mount refuses.

Sign in with Google

Auth::oidc adds a “Continue with Google” button to the login page, and to the sign-up page when the panel has one. The button leaves for Google, and Google sends the browser back to {prefix}/sign-in/google/callback, where the panel checks the answer and signs in the user an IdentityLinker names:

#![allow(unused)]
fn main() {
impl IdentityLinker for StaffAuth {
    type User = SignedStaff;

    async fn sign_in(
        &self,
        cx: &Cx,
        identity: &ProviderIdentity,
        ex: &mut dyn toasty::Executor,
    ) -> Result<Option<SignedStaff>> {
        // An identity linked before signs in as its staff member.
        if let Some(staff) = staff_linked_to(ex, &identity.issuer, &identity.subject).await? {
            return Ok(Some(staff));
        }
        // A new one links to the staff member holding the address, once Google verified it.
        let (Some(email), true) = (&identity.email, identity.email_verified) else {
            return Ok(None);
        };
        let Some(staff) = find_staff_by_email(cx, email).await? else {
            return Ok(None);
        };
        link_identity(ex, &staff, &identity.issuer, &identity.subject).await?;
        // … load the memberships and return Some(SignedStaff { .. })
        todo!()
    }
}

pub fn google_router(db: toasty::Db, cookie_key: &[u8]) -> Result<Router> {
    let google = OidcProvider::google(
        std::env::var("GOOGLE_CLIENT_ID").unwrap_or_default(),
        std::env::var("GOOGLE_CLIENT_SECRET").unwrap_or_default(),
    );
    let auth = Auth::custom(StaffAuth)
        .oidc(Oidc::new("https://admin.example.com", StaffAuth).provider(google));
    let mut builder = Router::builder()
        .with(db)
        // Seals each pending sign-in while the browser is at Google.
        .with(Key::from(cookie_key));
    builder.panel(Panel::new("admin").auth(auth))?;
    Ok(builder.build())
}

/// The staff member a row of the app's own identity table links `subject` at `issuer` to.
pub async fn staff_linked_to(
    _ex: &mut dyn toasty::Executor,
    _issuer: &str,
    _subject: &str,
) -> Result<Option<SignedStaff>> {
    todo!()
}

/// Stores a row of the app's own identity table linking `subject` at `issuer` to `staff`.
pub async fn link_identity(
    _ex: &mut dyn toasty::Executor,
    _staff: &Staff,
    _issuer: &str,
    _subject: &str,
) -> Result<()> {
    todo!()
}
}

Create an OAuth client of the “Web application” type in a Google Cloud project, and register https://admin.example.com/admin/sign-in/google/callback as its redirect URI: the base URL passed to Oidc::new, then the panel’s prefix. The base URL is the app’s public origin, for the same reason reset links use one rather than the request’s Host header. The router must hold a cookie Key, as for two-factor sign-in.

The linker is where the app decides who an identity is. Store the link as a row of your own, keyed by the identity’s issuer and subject: an address can change hands at the provider, its subject cannot. Link a new identity to an existing account only through an address the provider verified, or anyone who registers that address with the provider signs in as its owner. Returning None refuses the sign-in; creating the account there makes the button a sign-up. With several providers, linking by address trusts the least careful of them to verify it.

To admit the accounts of one Google Workspace domain only, check the identity’s hd claim in the linker, identity.claims.get("hd"); .param("hd", "example.com") on the provider only narrows the accounts Google’s page offers. .param("prompt", "select_account") lets a browser signed in to several Google accounts pick one, and .scope(..) asks for more than the address and name. ProviderIdentity::new builds an identity for a test of the linker alone.

Serve the panel on the base URL’s host only, redirecting any other such as www. to it: the pending sign-in’s cookie belongs to the host the browser started on, and the provider sends it back to the base URL. A browser holds one pending sign-in at a time, so a sign-in started in a second tab replaces the first’s. Callbacks count against the panel’s sign-in throttle.

A Google sign-in ends as a password one does: an account with a second factor answers the challenge, and the browser gets a new session. An account that has only ever signed in with Google has no password to confirm, so the pages that ask for it, such as the two-factor settings, need one set through the password reset first. OidcProvider::new signs in through any other provider that publishes an OpenID Connect discovery document. Auth::oidc lists what the mount refuses.

Acting as another user

Auth::impersonation lets a signed-in user act as another to see the panel as they see it. It is off until the app gives the rule deciding who may act as whom:

#![allow(unused)]
fn main() {
pub fn impersonating_panel() -> Panel {
    // An editor may act as a colleague who is not one, for half an hour at most.
    let rule = Impersonation::new(|_cx, actor: &SignedStaff, target: &SignedStaff| {
        actor.staff.editor && !target.staff.editor
    })
    .lifetime(std::time::Duration::from_secs(30 * 60));
    Panel::new("admin").auth(Auth::custom(StaffAuth).impersonation(rule))
}
}

The shipped Impersonate action places the button on a users resource whose model is the panel’s user type, and shows it only where the rule allows; a form of your own posts the user’s id as auth::IMPERSONATE_FIELD to {prefix}/impersonate. Every page then reads the target as the signed-in user, under a banner whose Stop restores the actor, and auth::impersonator names the actor in your own code.

Write the rule over both users: one that only checks the actor, such as “is support”, lets support act as an administrator too. Decide from the two users alone, since what cx signs in depends on when the rule is asked.

The rule is asked again on every request, and acting as someone ends with its lifetime, an hour unless you say otherwise and never more than a day. Nobody acts as themselves, as a user who may not enter the panel, or as a third user while acting as a second. On a panel that acts for tenants, the target must belong to no tenant the actor does not, so acting as them reaches nothing the actor could not already; Impersonation::across_tenants lifts that for a platform’s own staff. An actor who owes a step, such as a factor the panel now requires, is themselves again until they take it. The profile, two-factor, tenant settings, tenant registration and email-verification pages answer 403 meanwhile, so the actor never changes the target’s credentials.

Acting as someone is read-only. Every resource answers as if the panel mounted it ReadOnly, so its Create, Edit, Delete and action buttons are gone and their routes answer 403. No header action runs, on a resource or a page, and the notification bell offers nothing to mark or remove. tablo::can gives the same answers, so a page of your own that asks it before offering a write needs nothing more. A route of your own outside the panel’s resources and pages asks auth::impersonator. Impersonation::writable lets the actor write as the target, as far as the target’s policies allow; the credential pages stay closed either way.

A panel with the audit log records the start and the stop, an end the lifetime or the rule brings included, in the same transaction as the session’s change. Under a writable impersonation it also names the actor on every write made in between.

The session row stores the target in two nullable columns, impersonating and impersonating_until: an existing auth_sessions table gains them by ALTER TABLE.

Turning it off

#![allow(unused)]
fn main() {
pub fn open_panel() -> Panel {
    Panel::new("admin").auth(Auth::disabled())
}
}

Every panel route is then public and the login, sign-up, profile, password reset, two-factor, provider sign-in and tenant routes are not registered. Use it for public demos and tests only.

Tenancy

A tenant-owned resource shows each user only the rows of the tenant they act for. A user may act for each tenant PanelUser::tenants lists, as a Membership { tenant, name }; the provided AdminUser belongs to none, so a tenanted app signs in its own user table.

The request’s tenant is the membership the user selected, else the one PanelUser::default_tenant names, else their first; read it with tenant_id(cx), a TenantId, and the whole Membership with auth::membership(cx). A user with two or more memberships switches between them from a menu atop the sidebar (PanelUser::tenants). A panel acts for tenants when it offers a tenant registration or settings page, or mounts a tenant-scoped resource; any other acts for none, so tenant_id(cx) answers None there, in its custom pages and widgets too. No request header sets the tenant; server code such as a middleware or a test can, through a Tenant request extension or Tenant(id) on the Cx, where id is a TenantId: a bare Uuid does not compile there.

Auth::tenant_registration lets a signed-in user create a tenant, through a TenantRegistrar whose register writes the tenant and the user’s membership of it; required() sends a user with no membership there before anything else:

#![allow(unused)]
fn main() {
#[derive(FormInput)]
pub struct NewWorkspace {
    pub name: String,
}

impl TenantRegistrar for StaffAuth {
    type Input = NewWorkspace;
    type User = SignedStaff;

    async fn register(
        &self,
        _cx: &Cx,
        signed: &SignedStaff,
        workspace: NewWorkspace,
        ex: &mut dyn toasty::Executor,
    ) -> Result<Membership> {
        let id = create_workspace(ex, &workspace.name).await?;
        seat_staff(ex, signed.staff.id, id).await?;
        Ok(Membership::new(id.into(), workspace.name))
    }
}

pub fn workspace_panel() -> Panel {
    Panel::new("admin").auth(
        Auth::custom(StaffAuth)
            .registration(StaffAuth)
            .tenant_registration(TenantRegistration::new(StaffAuth).required())
            .tenant_profile(StaffAuth),
    )
}
}

Auth::tenant_profile adds a settings page for the tenant the request acts for, through a TenantEditor whose may_edit says which members may open it:

#![allow(unused)]
fn main() {
impl TenantEditor for StaffAuth {
    type Input = NewWorkspace;
    type User = SignedStaff;

    fn may_edit(&self, _cx: &Cx, signed: &SignedStaff, _workspace: &Membership) -> bool {
        signed.staff.editor
    }

    async fn fill(
        &self,
        _cx: &Cx,
        _signed: &SignedStaff,
        workspace: &Membership,
    ) -> Result<NewWorkspace> {
        Ok(NewWorkspace {
            name: workspace.name.clone(),
        })
    }

    async fn save(
        &self,
        _cx: &Cx,
        _signed: &SignedStaff,
        workspace: &Membership,
        renamed: NewWorkspace,
        ex: &mut dyn toasty::Executor,
    ) -> Result<()> {
        rename_workspace(ex, workspace.tenant.get(), &renamed.name).await
    }
}
}

Auth::tenant_registration and Auth::tenant_profile list what each page does and what the mount refuses.

Declare the resource’s tenancy with the column its rows carry their tenant in:

#![allow(unused)]
fn main() {
impl Resource for PostResource {
    type Model = Post; // has `tenant_id: TenantId`
    // …

    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .tenancy(Tenancy::column(lens!(Post.tenant_id)))
    }
}
}

That one declaration does three things:

  • The tenant check. Every handler of the resource answers 403 when the request has no tenant.
  • The scope. Every loader — list, export, detail, edit, delete, bulk delete, relationship options, related tables — adds tenant_id = <request tenant> to the resource’s query. A create sets the tenant column itself, so the record form leaves it out.
  • The write check. Before a create, edit, import or related form commits, the handler reads the written row back through the tenant scope. An overriding create_record that does not delegate to write_create, or an update_record that moves the row to another tenant, writes a row outside it: the transaction rolls back and the request answers 500.

The column is a TenantId field of the model, or Option<TenantId> for a nullable one, named by its lens. Do not repeat the filter in a ResourceDef::query narrowing. A resource over tenant-owned rows that declares no tenancy at all fails to mount, since it would serve every tenant’s rows; the mount errors say which declaration it needs. On a panel that acts for tenants, one that offers a tenant registration or settings page or mounts a tenant-scoped resource, every resource declares its tenancy: the mount cannot tell a tenant kept in a plain Uuid column from none.

A row that inherits its tenant. A comment has no tenant column of its own; it belongs to a post that does. Tenancy::via names the tenant through the relation, and the framework checks and filters exactly as it does for a column:

#![allow(unused)]
fn main() {
impl Resource for CommentResource {
    // …
    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            // …
            .tenancy(Tenancy::via(Comment::fields().post().tenant_id()))
    }
}
}

Nothing is stamped on create: a comment’s tenant is its post’s. The lens starts at a belongs_to relation, and the form declares that relation’s foreign key (post_id) as a relationship field over a tenant-scoped resource, so a submitted post must be one of the request tenant’s posts. Mounting the panel refuses a form that writes the key any other way, or a lens that does not start at a belongs_to.

A deliberately cross-tenant resource — a super-admin view, or the panel’s own users — declares Tenancy::none() and filters in ResourceDef::query. That gives up both the tenant check and the scope.

In your own code, load rows with scoped_query::<PostResource>(cx)?. It applies the tenant scope and answers 403 when the request has no tenant. Query::all() applies neither the tenant scope nor the panel’s narrowings.

Foreign keys are re-checked inside the write. A relationship field’s key must be one of the related resource’s records for the request: in its scoped query, which its list and its choices read. The create and edit handlers check it when they validate the form, and again inside the write’s transaction, so a related record deleted, moved to another tenant or hidden in between refuses the write with the same field error. A create_record or update_record the panel’s create and edit POSTs call needs no check of its own.

Adding a panel to an existing app

A panel mounts on the app’s own Topcoat router and reads the app’s toasty::Db, so an app with its own users and sign-in adds one without giving either up. This chapter covers what the panel needs from the app and the two ways to connect their sign-ins.

What the panel needs

  • A Topcoat router and a Toasty Db. Panel mounts on a RouterBuilder and its resources read Toasty models. An app on another framework runs the panel as a separate binary over the same database, or puts a Topcoat router in front of its existing service with TowerRoute.
  • Models over the app’s tables. A resource needs a toasty::Model. Name a table Toasty would not derive with #[table = "…"].
  • Tablo’s tables. Add AuthSession to the Db’s models, plus the others its features name, and generate a migration for them as Deployment shows. An app with a model named as one of Tablo’s, such as its own AdminUser, lists its models with toasty::models!.
  • A prefix of its own. The gate covers the panel’s prefix, and a #[layout("/")] would wrap the panel too: give the app’s layout a narrower path.

Mounting beside the app’s sessions

The panel keeps its sessions in its own __Host-tablo_session_{prefix} cookie. The router’s SessionTokenStore and SessionLifetime stay the app’s, so a sign-in, a sign-out or a session lifetime on one side never touches the other:

#![allow(unused)]
fn main() {
pub fn app_router(db: Db) -> Result<Router> {
    let mut builder = Router::builder()
        .discover() // the app's own pages and routes, and Tablo's
        .with(db)
        .layer(CookieLayer::new())
        .with(SessionLifetime(Duration::from_hours(24 * 14))); // the app's sessions, untouched by the panel
    builder.panel(Panel::new("admin").auth(Auth::external(AppSession)))?;
    Ok(builder.build())
}
}

Install the app’s own pathless layers before .panel(..), which installs Topcoat’s CookieLayer and RuntimeLayer.

Choosing who signs users in

The app hasUseThe user sees
a user table with passwordsAuth::customthe panel’s login form, a second sign-in
its own login page, SSO or magic linksAuth::externalthe app’s login page, once

Signing in through the app

Implement ExternalAuth over the app’s session and pass it to Auth::external:

#![allow(unused)]
fn main() {
/// The app's own sessions, as the panel reads them.
pub struct AppSession;

impl ExternalAuth for AppSession {
    type User = Employee;

    async fn current_user(&self, cx: &Cx) -> Result<Option<Employee>> {
        match session::token_hash(cx).await? {
            Some(hash) => employee_for(cx, &hash).await,
            None => Ok(None),
        }
    }

    fn login_url(&self, _cx: &Cx, next: &str) -> String {
        format!("/login?return_to={next}")
    }

    fn logout_url(&self, _cx: &Cx) -> String {
        "/sign-out".to_string()
    }
}
}

The user type implements PanelUser as with any authenticator, and its can_access_panel decides who among the app’s users enters: a user it refuses gets a 403 page and no panel session.

A visitor with no app session follows this path:

  1. A page under the prefix redirects to /admin/login?next=…, as on any panel.
  2. That route finds no app user and redirects to login_url, whose next is the route’s own URL.
  3. The app signs the user in and redirects to next.
  4. The route finds the app’s user, starts a panel session and lands on the page from step 1.

next reaches the app through the browser, so check it before following it:

#![allow(unused)]
fn main() {
/// Where the app's login page sends a user it just signed in.
pub fn landing(return_to: Option<&str>) -> &str {
    return_to.and_then(auth::safe_next).unwrap_or("/")
}
}

The gate asks current_user on every request, and serves a session only while it names the session’s user. Signing out of the app, or into another account, shuts the panel at its next request, with no call to auth::revoke_sessions_for_user. For that to reach a live connection, which keeps the cookies of its handshake, current_user must consult a session the server holds. A browser that returns to the same app user finds its panel session, and its tenant, as it left them. The app’s session cookie must reach a page opened from another site, as SameSite=Lax does; behind SameSite=Strict a followed link finds no user.

The shell’s Sign out ends the panel’s session alone, then sends the browser to logout_url by GET, on any origin. Point that at a route that ends the app’s session, an SSO provider’s end-session URL included, or at a page of the app’s that offers to. While the app’s session lives, the next visit to the panel signs the user in again.

A browser holds one session on each panel, so entering this panel leaves a session held on another as it is.

An app page outside every panel that calls a panel’s shard names no panel. It runs on the session the browser holds; with sessions on several panels it runs as anonymous, unless only one of them declares the shard.

The app owns the account, so mounting refuses Auth::registration, Auth::password_reset, Auth::email_verification and Auth::two_factor beside Auth::external. The panel’s tenant menu, profile page and notifications work as on any panel.

Keep the gate on

Auth::disabled() with a layer of the app’s over the prefix leaves the panel open: its search and other endpoints serve at /_topcoat/runtime, outside the prefix, and answer anyone. Auth::external puts the same check in front of both.

Data access

The panel loads rows on its own pages. This chapter covers querying Toasty from your code: a page, a record function, or a public page. The Toasty guide covers the query API in full.

Getting the database

with(db) registers the Db on the app’s router, where every panel mounted on it reads it; tablo::db::db(cx)? returns it. Cloning a Db is cheap, and statements take it by &mut:

#![allow(unused)]
fn main() {
    let mut db = tablo::db::db(cx)?;
    let users = User::all().exec(&mut db).await?;
}

Inside a record function, run statements through the transaction you were handed (ex), never through a second handle: a single-connection pool such as sqlite::memory: would wait forever for the connection the transaction holds.

Querying

#![allow(unused)]
fn main() {
    User::filter(User::fields().email().eq("ada@example.com"));
    User::filter(User::fields().name().starts_with(prefix)).order_by(User::fields().name().asc());
}

Toasty binds values as parameters. If you build a LIKE pattern from user input, escape %, _ and your escape character first and pass it with like_with_escape, as the table search does.

Load a resource’s rows through scoped_query. See Tenancy.

A public page has no resource behind it, so it states its own filters, tenant included:

#![allow(unused)]
fn main() {
    let posts = Post::filter(Post::fields().status().eq(PostStatus::Published))
        .include(Post::fields().author())
        .exec(&mut db)
        .await?;
}

Relations

Toasty loads a relation only when the query includes it. Include every relation you read, in the same query:

#![allow(unused)]
fn main() {
    let posts = Post::all()
        .include(Post::fields().author())
        .exec(&mut db)
        .await?;
    for post in &posts {
        let _name = &post.author.get().name; // no extra query
    }
}

Reading a relation that was not included panics in get(); check is_unloaded() first where a missing include is possible. A table or detail column shows a relation with RelationColumn, which declares its include, or counts one with CountColumn, which queries the count: see Tables.

A resource’s table on your own page

A page can render a resource’s list table over its own query — here, only featured posts — with the same columns, filters and row actions as the resource’s list:

#![allow(unused)]
fn main() {
    let table = tablo::wired_table::<PostResource>(cx)?;
    let query = scoped_query::<PostResource>(cx)?.filter(Post::fields().featured().eq(true));
    let body = table.render(cx, query).await?;
}

wired_table is the table the request’s panel mounted for the resource, with the row actions its policy allows, so the page and the list cannot drift apart. WiredTable::render renders it live, as the resource’s list is: a sort or search reruns your page in place. A page that renders two tables gives each a prefix with .prefixed("posts").

Outside a panel

A request outside every panel’s prefix, such as a public page, belongs to no panel, however many the router mounts: scoped_query answers it with an error naming the resource. Keep the handle mounting the panel returns (below) on the router, and enter the panel for the request:

#![allow(unused)]
fn main() {
let cx = admin.enter(cx);
let posts = scoped_query::<PostResource>(&cx)?;
}

The entered context answers as the panel mounted its resources, and runs no auth gate: PanelHandle::enter has the details.

Outside a request

scoped_query, can, write_create and the other entry points that answer from a mounted def read the resources a panel mounts, so code that runs outside a request, such as a background job, reads them from the panel the router mounts. builder.panel(..) returns that panel’s PanelHandle, which holds the router’s database and the panel’s mounted resources and is cheap to clone into a job:

#![allow(unused)]
fn main() {
pub fn admin_router(db: Db) -> topcoat::Result<(Router, PanelHandle)> {
    let mut builder = Router::builder().discover().with(db);
    let admin = builder.panel(
        Panel::new("admin")
            .resource::<PostResource>()
            .resource::<CommentResource>()
            .resource::<AuthorResource>(),
    )?;
    Ok((builder.build(), admin))
}
}

admin.context() returns a context holding the database and those resources, without declaring the panel again. Add a tenant with .with(Tenant(id)):

#![allow(unused)]
fn main() {
    let cx = admin.context().with(tablo::Tenant(tenant));
    let mut ex = tablo::db::db(&cx)?;
    let drafts = scoped_query::<PostResource>(&cx)?
        .filter(Post::fields().status().eq(PostStatus::Draft))
        .exec(&mut ex)
        .await?;
}

A context is one unit of work, as a request is, so build one per job run; it carries no signed-in user. PanelHandle::context says what it holds and what a policy sees. The url helpers answer in it, so a job’s mail links to url::page::<BillingPage>(&cx) rather than a spelled path, and the context carries the router’s BaseUrl to make that link absolute. Panel::handle(&db) builds the same handle from a panel no router mounts, such as a test’s.

Schema setup

db.push_schema().await? creates every registered table, which suits a prototype or a test. A production app manages its schema with toasty-cli migrations.

Rendering rules

Topcoat may render a page’s regions concurrently and re-render them in place, so code that renders follows three rules:

  • No side effects. Pages, layouts and components only read. Writes belong in record functions or app routes.
  • Deterministic output. No HashMap iteration order, current time or random values in a region that re-renders: a re-render must produce the same markup for the same data.
  • Untrusted signals. A value read on the server with a signal’s get() or read() comes from the client. Validate it like any request input.

Share a query between components of one request with Topcoat’s #[memoize], and add a Toasty #[index] to columns you filter on.

A table updates through a rerun of its page, which runs the page’s layers and checks like any request. Topcoat serves a shard at its own runtime path, where the page’s checks do not run: a shard you write starts with auth::guard(cx)?, and checks can_list::<R>(cx) before it lists R’s rows. Declare it on its panel with Panel::endpoint, which says which panel a shard runs as otherwise.

Organizing an app

Your first panel fits in one file, and an app with a few resources can stay that way. This chapter is for the app that outgrows it: where its models, resources, panels and settings go, and which modules import which. Tablo checks none of it. Mounting checks what you declare, wherever it lives (see Mount errors), so these are conventions, not rules.

The Tablo demo follows this layout: a shop, a blog, HR and projects, served by an admin panel for staff and an app panel customers sign up on. Its paths are this chapter’s examples.

Modules by domain

Group the code by the part of the business it serves, not by the kind of item it is:

src/
├── main.rs         reads the configuration, connects, seeds, serves the router
├── lib.rs          the modules, and models(): every model the database maps
├── config.rs       every environment variable, read once
├── router.rs       mounts the panels on one router
├── panels/         one function per panel, and what the panels share
├── access.rs       what each role may do in each domain
├── shop/
│   ├── mod.rs      the names the panels and other domains use
│   ├── models.rs   the domain's Toasty models and their enums
│   ├── brand.rs    one resource: its definition, form and record functions
│   └── order/      a resource that outgrew its file
│       ├── mod.rs
│       ├── actions.rs
│       ├── items.rs
│       └── pipeline.rs
├── blog/
├── hr/
├── shared/         what two domains or more use
└── seed/           the demo data

A change to orders then touches shop/order/. Split by kind, into models/, resources/ and actions/, the same change touches three directories, and none of them says what belongs to orders.

A domain module

  • models.rs holds the domain’s Toasty models together. A relation is declared on both of its models (has_many on one, belongs_to on the other), so the two sides sit in one file. A model may name another domain’s model: shop products carry blog comments.
  • One file per resource holds the resource, its RecordForm, its record functions and its actions. The resource’s definition and the form it renders change together.
  • mod.rs declares the files privately and re-exports what the panels and the other domains name: the resources, the models, a widget. Its doc comment says what the domain holds and which sidebar group its resources form.

A resource becomes a directory when one file no longer reads well: its actions move to actions.rs, a widget to its own file, and the resources its detail page shows as related tables next to it. Those child resources call ResourceDef::without_navigation(), so they live with their owner rather than in the sidebar: shop/order/items.rs holds an order’s lines.

Panels

panels/ has one function per panel that returns its Panel, and a function for what every panel shares, such as the brand, the locales and the translations:

#![allow(unused)]
fn main() {
pub fn admin_panel(config: &Config) -> Panel {
    shared(Panel::new("admin"))
        .auth(Auth::custom(DemoAuth))
        .resource::<shop::ProductResource>()
        .resource::<shop::OrderResource>()
        // …
        .resource::<hr::EmployeeResource>()
        // …
}
}

The panel picks its resources, and a resource never names a panel: a resource registered by several panels is declared once. Register a domain’s resources together. Entries of equal navigation_order keep their registration order, and a sidebar group sits where its first entry lands, so the registration order is the sidebar’s.

router.rs builds the router: the database, the cookie key, mail, assets and each panel. main only reads the configuration, connects and serves.

Access

Put the policies in one module, access.rs, and give each resource its policy from there:

#![allow(unused)]
fn main() {
ResourceDef::new()
    .navigation_group(tablo::text!("navigation-shop"))
    .policy(access::policy(Domain::Shop))
}

One function answers every ability of every resource of a domain from the user’s role, so which role reaches what is one table rather than a closure per resource. A page asks the same module through PageDef::access: the shop dashboard opens to access::reaches(cx, Domain::Shop). Building a policy covers the policies themselves.

Configuration

Read the environment in one place. config.rs holds a Config struct that main builds once, at start, and passes by reference to the router and the panels. A variable set to a value the app cannot use then fails at start, not on the first request that reads it, and config.rs lists every variable the app reads.

Imports go one way

main → router → panels → domains → shared
seed → domains
  • Domains import shared and each other’s models, never a panel, the router or the seed.
  • shared imports no domain. Code that one domain uses belongs in that domain, so shared holds only what two or more use.
  • The seed imports the domains, and nothing imports the seed but main.

A domain that imported a panel would tie its resources to that panel. Keeping the arrows one way also means a domain reads on its own: its directory holds everything a resource does, and the panel only says where it appears.

Translations

Each panel loads one Fluent catalog per locale with Panel::translations, so the app keeps one file per locale under locales/ and includes it with include_str!. Panels that share their words load the same catalogs from the shared panel function. Tablo derives a label’s key from what it labels (field-…, option-…), so those keys follow the models rather than the files; Labels lists them.

Extension points

The seams for reaching outside a resource declaration. Five have full sections of their own: Authenticator, ExternalAuth, Uploader, Panel::layout_shell, and wired_table. The remaining three are documented here.

The traits that add a new kind of building block live in tablo::extend: a Column, a Filter, a Control, an OptionSource and a TypedValue. The built-in columns and filters and the Toggle control implement the same traits.

Relationship option sources

A relationship choice field loads its options through tablo::extend::OptionSource. Every resource is one, answering from its def as the request’s panel mounted it, so a choice over a resource offers what its list would show the same user. Implement it for a source that is not a resource, such as a lookup table no panel lists; the trait’s page says what each method states and how a load is bounded.

Table state values

tablo::Sort (?sort=<column>&dir=asc|desc), TableState::page and per_page (?page=, ?per_page=), and tablo::Cursor (?after= / ?before=) are the parsed sort and pagination of a list URL; see Tables. tablo::TablePage::position says where a numbered page sits.

Notifications

An action’s result flashes a tablo::Notification, rendered in the panel shell and stored as a one-time hardened cookie. Build one with Notification::success / error / info / warning plus .description(), and store it with tablo::notification::set_notification; see Security.

Security

What Tablo does by default, and what your deployment must provide for those defaults to hold.

Your deployment must provide

  • HTTPS. The session, CSRF and notification cookies are __Host- cookies marked Secure. Browsers accept them over plain HTTP only on localhost; anywhere else, without HTTPS, the browser drops them and every form POST fails its CSRF check with 403.
  • The client’s address behind a proxy. Tablo throttles sign-ins per login and client address. Behind a reverse proxy, trust it with the router’s TrustedProxies so the address is the client’s; otherwise a guesser who knows a login can lock its owner out. The first sign-in that carries a forwarding header the router ignored logs a warning.
  • Per-IP and multi-replica rate limiting at your proxy or firewall, for what the panel’s throttle does not count: LoginThrottle lists it.
  • The panel gate, whoever signs users in. Put a panel behind an app’s own sign-in with Auth::external, not with Auth::disabled() and a layer of your own: the panel’s endpoints serve at /_topcoat/runtime, outside its prefix, and only its gate covers them.
  • Session revocation. Call auth::revoke_sessions_for_user when a password changes outside the panel’s edit form, in a custom action, or a custom user’s credentials change. An edit form that changes an AdminUser’s, or another PasswordAccount’s, email or password hash ends that user’s sessions itself, and deactivating one ends them at its next request.
  • Deleting an account. Call erase_user in the transaction that deletes the user, rather than deleting Tablo’s tables by name: it deletes the user’s rows from every table Tablo ships, the ones a later release adds included.

Requests and writes

  • Every panel POST, login and logout included, verifies a double-submit CSRF token before any write it asks for; a missing or wrong token answers 403.
  • Topcoat’s runtime calls carry no CSRF token: the notification bell’s procedures, the search and notification shards, and any shard or procedure the app adds. The router’s OriginPolicy, on by default, refuses them from another site. Keep it: a router built with OriginPolicy::dangerous_disable, or exempting /_topcoat/runtime, leaves them open to cross-site requests, and Tablo cannot tell.
  • Delete and bulk-delete POSTs also require the confirm=1 marker the confirmation dialog sends. It prevents accidental deletes; it is not a security boundary.
  • A form POST with a key the form does not declare answers 400, so a client cannot write a field the form does not show, such as role or tenant_id (RecordForm).
  • Update, delete and custom action handlers load the target through the resource’s scoped query inside the write’s transaction and check policy on that row. See Policy.
  • Table search binds the term as a parameter; no user input is interpolated into SQL (Table).

Authentication

  • Passwords are hashed with Argon2id, and a login for an unknown email takes as long as a wrong password: PasswordAuth.
  • Sign-ins are throttled per login and client address, five a minute unless Auth::throttle says otherwise, and, opt-in, per login across addresses with Auth::account_throttle, which lets anyone who knows a login keep its owner out; sign-ups per address (Auth::sign_up_throttle).
  • Sessions are stored server-side as a hash of the cookie’s token, and replaced on login and on sign-up: AuthSession.
  • A redirect after login follows next only to a same-origin path.
  • A two-factor challenge ends after five wrong codes in a row, later codes wait longer each time, up to an hour, and the account is mailed that its password was used. Whoever holds the password can keep the owner’s app codes waiting until the owner changes it: Auth::two_factor.
  • A Google or other OpenID Connect sign-in is bound to the browser that started it by a sealed cookie, its state and its PKCE verifier, and its ID token to the sign-in by its nonce. The token comes from the provider’s token endpoint over TLS, and the app’s linker decides which account an identity is. A pending sign-in lasts ten minutes, and its callbacks count against the sign-in throttle: Auth::oidc.
  • Acting as another user is off until the app gives a rule, which every request asks again. It lasts an hour by default, never nests, writes nothing unless the app makes it writable, keeps the actor off the target’s credential pages, and the audit log names the actor: Auth::impersonation.

Several panels, one user type

Two panels whose authenticators load the same user type share that type’s accounts. What each panel keeps to itself, and what it does not:

  • Sessions are per panel. A session belongs to the panel that signed the user in; another panel’s gate treats the request as anonymous (AuthSession).
  • Accounts and credentials are not. A sign-up on one panel writes an account every sibling panel looks up. The same password signs in to each panel that admits the user, and a password change or reset on one ends the user’s sessions and reset links on each.
  • Access is the user type’s to decide, per panel. PanelUser::can_access_panel receives the panel’s PanelId, so one type can admit staff to /admin and every customer to /portal. A PanelId equals its prefix in any spelling, "admin" or "/admin/", and offers no string to match a part of. Name each panel and answer false for the rest: a panel added or renamed later then admits nobody until it has a rule.
  • A second factor is shared too. A factor set up on one panel is asked on every sibling that installs Auth::two_factor, so a password alone neither signs in there nor sets up a factor of its holder’s. Turning it off on one panel turns it off on all, and takes a code.
  • The weakest panel is the floor. Email verification, two-factor sign-in, requiring a factor and tenant registration are each declared per panel. A sibling without Auth::two_factor asks no account for a code, so a password alone signs in there. An account that holds no factor signs in to every sibling with its password, and one that requires a factor lets the holder set up their own, which then stands on each. A sibling that mails no codes asks an account set up for mailed codes for a recovery code.

The sharing follows the user type, not the table. Two user types over one table share passwords, yet a password change on one type’s panel ends no session on the other’s. To give two panels separate credentials, give each its own user type, over its own table, with its own Authenticator: a staff password then signs in to no customer panel, and a customer panel’s weaker sign-in reaches no staff account.

Several panels, one origin

Each panel keeps its session in its own cookie, and the page a request comes from decides which cookie counts. That decides which session a request means; it does not separate panels. They share an origin, so a script running on one panel’s page, or on any page of the host app, can send requests to another panel as whoever the browser is signed in as there. HttpOnly keeps the cookie from being read, not from being sent.

Put panels of different trust on separate hosts. One binary serves both when each panel names its host:

builder.panel(Panel::new("admin").host("admin.example.com"))?;
builder.panel(Panel::new("app").host("app.example.com"))?;

A panel bound with Panel::host answers 404 on every other host: its pages, its sign-in, the directories it serves and its runtime endpoints. No admin session starts on the customer host, and __Host- cookies stay on the host that set them, so a cross-site script on the customer panel has no admin session to use. Point both names at the binary, and have the reverse proxy pass the browser’s Host header on: the panel reads no X-Forwarded-Host.

The app’s own routes outside the panels still answer on both hosts. A script injected on one of them at the admin host acts on the admin panel, so keep what the admin host serves as trusted as the panel.

Responses

  • Headers. Every response under the panel prefix carries a Content-Security-Policy that loads script files from the panel’s origin only and lets no other site frame the panel or receive its forms, along with X-Content-Type-Options: nosniff, Referrer-Policy: same-origin and Cache-Control: no-store, so the back button after sign-out shows no record. The policy does not stop an injected script; escaping does. Topcoat’s live regions need 'unsafe-inline' and its client expressions need 'unsafe-eval', so dropping either breaks the panel, as Panel::DEFAULT_CONTENT_SECURITY_POLICY details. What a custom policy can tighten is where an injected script sends data: with no images, fonts or media on other hosts, set img-src, font-src and media-src to 'self' plus the data: and blob: sources the default has. Panel::content_security_policy replaces the policy, for assets on another origin or a panel framed by an intranet, and lists the responses the headers miss. Behind a proxy that serves HTTPS only, turn on HSTS with Panel::strict_transport_security.
  • Compression. Pages are compressed, and a page shows text the URL chooses, such as a search. An observer of the encrypted traffic who also makes the browser load chosen URLs can guess, from response sizes, a value that repeats on every load of such a page (BREACH). The panel’s own secrets change on each render: a form carries the CSRF token masked afresh (csrf::mask), and an upload’s URL is signed under a new nonce. A record’s values do repeat, so a column showing a secret, such as an API key, exposes it on the list page. Compression::disable() on the router turns compression off; a proxy that compresses has the same exposure.
  • Search engines neither index a panel’s pages nor follow their links, per the robots tag Panel documents.
  • Redirects. Return Err(redirect(..)) (307) from a GET and Err(see_other(..)) (303) after a write, so a reload does not repeat it. A redirect raised after streaming started becomes a window.location.replace. A failed page load shows the panel’s error page; wrap part of a page in error_boundary to show a fallback in its place instead.
  • Notifications are one-time flash cookies set on the redirect after a write and consumed by the next page, so a reload does not show them again.
  • Rich text is the one stored value Tablo renders as HTML, cleaned to the elements its toolbar’s tools produce. A page of your own renders one through rich_text::clean, never unescaped as stored.

Uploaded files

  • A file field stores only a value that came from a file part, never a path typed into the form, and renders a stored value as a link only when it is a root-relative path or an http(s) URL: Uploader.
  • Panel::uploads_dir serves a file only at a signed URL that expires within two hours, which a page renders after checking the user may see the record, so a link copied into a chat or a log stops working. The signature covers a path, not a record: a column showing a value users type signs whatever path they type, so show stored uploads only from file fields: Panel::uploads_dir.
  • Files served with Panel::serve_dir or uploads_dir share the panel’s origin, so they carry headers that make an uploaded HTML or SVG file download instead of running script. A serve_dir directory is public unless it sits under the panel prefix: Panel::serve_dir.

Deployment

A deployed panel is one release binary, the asset bundle built with it, and a database whose schema migrations keep current. Security lists what the host must provide around them: HTTPS, the client’s address behind a proxy, and rate limits.

Build the binary and its bundle

topcoat asset bundle --release -p my-app

The command builds the release binary and writes its asset bundle to assets/ beside it, in target/release/. Ship target/release/my-app and target/release/assets/ together: the bundle holds the stylesheet, the font, Topcoat’s runtime and the shell’s scripts under names that one build computed, so a bundle from another build does not match. AssetBundle::load() reads the directory beside the executable; AssetBundle::load_dir(path) reads one elsewhere. A package with several binaries, such as the migration binary below, names the server’s with --bin my-app.

Tablo’s prebuilt stylesheet needs no build step. An app that builds its own compiles it earlier, by tablo_build::tailwind() in build.rs, which downloads the Tailwind CLI into Topcoat’s cache on its first run: a build machine needs network access once.

Migrate the database

db.push_schema() creates every table from scratch, which suits a prototype and a test, not a database holding data. In production, generate SQL migrations with Toasty’s migration CLI and apply them before the new binary starts.

toasty-cli is a library: the app builds its own small binary around the same Db its server uses, so the migrations cover every model the panel reads, the ones tablo::models! adds included:

// src/bin/migrate.rs
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let db = toasty::Db::builder()
        .models(tablo::models!(my_app::Post))
        .connect(&std::env::var("DATABASE_URL")?)
        .await?;
    toasty_cli::ToastyCli::with_config(db, toasty_cli::Config::load()?)
        .parse_and_run()
        .await
}
  • cargo run --bin migrate -- migration generate diffs the models against the last snapshot and writes a migration; commit it.
  • target/release/migrate migration apply runs the pending migrations; run it on each deploy, before the server starts.

The Toasty guide covers Toasty.toml, renames and the other subcommands. A new database has no user to sign in with: seed the first one with auth::create_admin, from a one-off binary or a startup step that runs when no admin exists.

Run it

  • topcoat::start binds HOST:PORT, 127.0.0.1:3000 by default; in a container set HOST=0.0.0.0.

  • A panel sends its auth mail after the response, which the server does not wait for when it stops. Await settled once it returns, so a deploy does not drop a reset link a visitor was just promised:

    topcoat::start(router.clone()).await?;
    tablo::settled(&router).await;

    A crash still loses that mail, and a mail server that is down fails it. An AuthMailDelivery installed with AuthMail::delivery covers both: it writes each letter to the app’s queue in the transaction that records the letter’s token, and a worker sends it. The jobs feature ships one, AuthMailQueue, on the durable queue tablo::jobs keeps in the app’s database:

    let queue = tablo::jobs::AuthMailQueue::new(&cookie_key);
    let mail = AuthMail::new(from, "https://app.example.com").delivery(queue.clone());
    // In the worker, beside the server or in a process of its own:
    let worker = tablo::jobs::Worker::new(&panel)?
        .auth_mail(&queue)
        .context(move |cx| cx.with(Mailer::new(transport.clone())));
  • Terminate HTTPS in front of the binary: the panel’s cookies are Secure, so without it every form POST fails its CSRF check.

  • Load the router’s cookie Key from a secret holding at least 64 random bytes (decode a hex or base64 secret first: its text has fewer bits than its length), never from Key::generate() and never committed: it seals two-factor secrets and queued auth mail, so a key that changes on restart, or differs between replicas, leaves every enrolled account unable to sign in, and a key that leaks lets its holder read them.

  • Give panels of different trust their own origins: bind each to its host with Panel::host, and point both names at the binary. Panels on one origin are not isolated: a script on one can act on the others. A customer panel beside an admin panel is the case to split; panels for the same staff can share a host.

  • Pages are compressed with gzip or brotli for a browser that accepts them: a list page is mostly repeated markup, and shrinks about fifteen times. Where a proxy or a CDN compresses already, pass Compression::disable() to Router::builder().with(...).

  • Behind a reverse proxy, install TrustedProxies on the router, so the sign-in throttle counts the client’s address and not the proxy’s.

  • Keep uploads on storage that outlives the binary: the directory Panel::uploads_dir writes to is a volume, or the Uploader writes elsewhere. Its links are signed with a key derived from the router’s cookie Key, so replicas that should open each other’s links share that Key.

  • Several replicas share the database, and sessions with it. Each throttle counts in each process by default: Auth::throttles_in_database keeps every throttle’s counts in the database, where every replica reads them, and LoginThrottle::in_database one throttle’s; without them, limit attempts across replicas at the proxy.

  • The notification bell wakes over an in-process channel, as ADR-0028 records: a send, a read or a sign-out on one replica re-renders only the bells connected to that replica. A bell connected to another one shows the new state when its page reloads or its own replica next wakes it; a session revoked elsewhere stops at that wake, before it shows anything new.

Mount errors

.panel(..) checks every declaration before the panel serves a request, and returns a MountError listing each mistake it found, not only the first. A mistake the type system cannot catch, such as a unique field without a unique index or a slug two resources share, therefore stops the app at startup instead of answering one request wrong.

Each DeclarationError names the resource or page type that declares it (None for the panel’s own configuration), the Site of the declaration it is in, such as the table or the form, and a DeclarationErrorKind, whose Display is the message the app prints:

panel '/admin' cannot mount:
  - `showcase::app::PostResource` form: field `slug` is marked unique, but no unique index covers its column: …

DeclarationErrorKind lists every kind, when the mount refuses it and how to fix it. A kind that groups several faults, such as Tenancy or ActionInput, carries a fault enum that says which one, with its own fix.

A test matches on the kind rather than the message; see Testing. The kinds are #[non_exhaustive], so a match on them ends in _.

One kind, NotMounted, refuses no mount: it answers a request with a 500 when app code asks for a resource the context’s panel does not register, such as through scoped_query from a public page that entered no panel (Data access).

Troubleshooting

A mistake in a declaration refuses the mount with a message naming it; Mount errors lists each one. This chapter covers what goes wrong once the panel mounts.

Startup

SymptomCauseFix
cargo run stops with an error about a missing asset bundleAssetBundle::load() reads assets/ beside the executable, which cargo build does not writerun the app with topcoat dev, or topcoat asset bundle first; see Deployment
the build script fails fetching Tailwindtablo_build::tailwind() downloads the Tailwind CLI on its first runbuild once with network access; the CLI stays in Topcoat’s cache

Pages

SymptomCauseFix
pages render unstyled, and delete confirmations do not openthe router has no asset bundle, or the panel no shell_assetsinstall both: Assets
a Tailwind class in your own page has no styleTablo’s prebuilt stylesheet holds only Tablo’s classes, and an app’s own scans only the sources styles.css namesbuild the app’s own stylesheet (The stylesheet), and add an @source line for them
a page renders a document inside a documentthe app declares its own #[layout] at the panel prefixdrop it, and frame pages with Panel::layout
a resource is missing from the sidebarits policy does not allow ViewAny for this userallow ViewAny; see Policy
no Create button, or the create page answers 403the policy does not allow Create, or the resource’s Form is NoFormallow Create and name a record form
a record’s detail page answers 404the resource declares without_page(ResourcePage::View)drop it, and declare a detail if the default lists no column
`Post` declares no default columnsthe resource’s model does not implement PanelModeladd #[derive(tablo::PanelModel)] to the model
a tenant-owned resource answers 403 everywherethe request has no tenant: the user has no membership, and the shipped AdminUser has nonesign in your own user table, whose PanelUser::tenants lists memberships
the export answers 413the search and filters match more rows than the export writesnarrow the list before exporting

Signing in and forms

SymptomCauseFix
every form POST answers 403 off localhostthe session and CSRF cookies are Secure, so the browser drops them over plain HTTPserve the app over HTTPS
the browser bounces between the app’s login page and {prefix}/loginExternalAuth::current_user answers None on panel requests for a user the app signed inread the same session the login page writes; install the app’s cookies and sessions
the browser bounces the same way, with a new auth_sessions row each timethe browser refuses __Host-tablo_session_{prefix}, which needs HTTPS or localhostserve the panel over HTTPS
global search and the notification bell answer 401 for a user signed in to two panelsa proxy strips the Referer or cuts it to the origin, so the request names no panel and two sessions dispute itkeep the Referer’s path on same-origin requests
a live shard answers 500 and the log says a runtime socket opened outside Tablo’s stampthe app adds a RuntimeLayer after .panel()add it first, or leave it to the panel
a user signs in and gets 403the user has no panel access: AdminUser.active is false, or your PanelUser denies itactivate the user
sign-ins answer the wrong-password message for a correct passwordthe throttle allows five attempts a minute per login and address, and Auth::account_throttle, when set, counts per login across addresses; behind a proxy every client shares the proxy’s addresswait out the window; install TrustedProxies on the router
a form POST answers 400it carries a key the form does not declare: a custom control posting an extra input, or a hand-built requestpost only the record form’s keys
a route you added under the prefix redirects to the login page or answers 401the auth gate covers every path under the panel prefixsign in, or move a public route outside the prefix

Testing and benchmarks

Testing a panel

Test a panel over HTTP, in memory: mount builds the router against a test database, and TestClient sends it requests. The client carries cookies, a tenant and a CSRF token; sign_in signs it in as a user, log_in goes through the login form, and submit and submit_multipart post a form with its CSRF pair. The testing module also builds form bodies and reads responses back: the table’s rows and row_keys, why a field was refused (field_error), the flash notification, why a table is empty (empty_table), and whether a button asks first (confirms_first). An app reaches it as tablo::testing through the facade’s testing feature; enable it for tests only:

[dev-dependencies]
tablo = { version = "0.11.1", features = ["sqlite", "testing"] }
#![allow(unused)]
fn main() {
use tablo::{auth::create_admin, testing::{TestClient, mount_with_handle}};

#[tokio::test]
async fn books_cannot_be_deleted() {
    let mut db = seeded_db().await; // your fixture: an in-memory database with rows
    let book = first_book(&db).await;
    // `mount_with_handle` builds the router an app does, beside its own pages and routes, and
    // keeps the mounted panel, which the client reads its URLs from.
    let (router, panel) =
        mount_with_handle(db.clone(), Panel::new("admin").resource::<BookResource>())
            .expect("mount the panel");
    let admin = create_admin(&mut db, "admin@example.com", "secret", "Admin")
        .await
        .expect("seed the admin");
    // `sign_in` records a session for `admin`, as a successful login does.
    let client = TestClient::new(&router)
        .sign_in(&db, "admin", &admin)
        .await
        .panel(&panel);
    let books = client.resource::<BookResource>();

    let list = books.list().await;
    assert_eq!(list.status(), 200);
    assert_eq!(list.rows().len(), 1);

    // `delete` posts the confirmed delete to the record's route, with the CSRF pair.
    let reply = books.delete(&book).submit().await;
    assert_eq!(reply.status(), 403); // the policy does not allow `DeleteAny`

    let books = Book::all().exec(&mut db).await.expect("list books");
    assert_eq!(books.len(), 1); // nothing was deleted
}
}

client.resource::<R>() sends typed requests to one resource: it loads its pages, builds its form posts from the form’s derived field enum (.set(BookFormField::Title, "Emma")), and posts its deletes and actions. Each URL comes from the panel, so a test follows a renamed slug, fails to compile on a renamed field or action, and panics naming the resource when the panel serves no such page instead of asserting on a 404. A submission answers with a Reply that reads its status, redirect, notification, rows and field errors, and follow() loads the page a redirect names. ResourceClient, Submission and Reply list the methods.

The free functions remain for what the typed client does not cover: a raw body, a request to a route the panel does not mount, a header to assert.

  • Cover every ability your policy decides with a request it allows and one it refuses, and assert on the database as well as the status code.
  • Cover query() scoping by seeding a row the scope excludes and asserting that the list, the detail page and a delete all miss it.
  • Tenancy. client.tenant(id) scopes a request to a tenant, the way a signed-in user’s tenant would.
  • Signed-in requests. client.sign_in(&db, "admin", &user) signs the client in as user with no login form and no password hash (TestClient::sign_in).
  • Declaration mistakes. A panel that refuses to mount returns a MountError inside the router builder’s error. refusal lists its mistakes; match on each one’s DeclarationErrorKind rather than on its message:
#![allow(unused)]
fn main() {
#[tokio::test]
async fn the_panel_refuses_a_db_without_the_auth_models() {
    let db = Db::builder()
        .models(toasty::models!(Book))
        .connect("sqlite::memory:")
        .await
        .expect("connect");
    // Auth is on, and the `Db` does not register its models.
    let mistakes = refusal(mount(db, Panel::new("admin").resource::<BookResource>()));
    assert!(matches!(
        mistakes[0].kind,
        tablo::DeclarationErrorKind::MissingAuthModels { .. }
    ));
}
}

examples/showcase/tests/ is a complete suite covering lists, forms, deletes, filters, export, tenancy, uploads and authentication; its common module holds the fixtures above.

The browser scripts

tablo-ui’s searchable-select script is a plain browser script with no build step. Its unit tests run on Node’s built-in runner:

node --test crates/tablo-ui/assets/selects.test.js

Benchmarks

The benchmark renders a 50-row list with two included relations, under tenancy and policy, through the same path as the panel’s list page:

cargo run --manifest-path benchmarks/tablo/Cargo.toml -- --bench
./benchmarks/scripts/bench.sh   # adds an HTTP run with `oha`

The target is under 40 ms at the median on local SQLite. It is a reference, not a pass/fail gate: the harness prints the target beside the measurement. Results are written to benchmarks/results/, which is not committed. benchmarks/README.md covers the setup, the optional PostgreSQL run and the method.