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
| Call | Effect | See |
|---|---|---|
Panel::new(prefix) | the panel at /{prefix} ("" mounts at /admin) | |
resource::<R>() | registers a resource’s routes and sidebar entry | Resources |
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 theme | Branding |
dark_by_default() | starts a first-time visitor dark | Branding |
environment(Environment) | names the deployment, such as staging, on every page | Branding |
login_hint(text) | adds a line under the sign-in card | Branding |
locales(locales) | lists the locales the panel offers, the default first, English by default | Translations |
translations(locale, ftl) | adds the app’s Fluent catalog for a locale | Translations |
time_zone(zone) | sets the zone a user without their own reads and enters times in, UTC by default | Forms |
user_menu_item(NavigationItem) | adds an entry to the user menu, above Sign out | The shell layout |
auth(Auth) | replaces or disables the built-in password login | Policy, auth, tenancy |
uploads(uploader) | sets where file fields store their bytes | Forms |
serve_dir(path, dir) | serves a directory of files, publicly unless the path sits under the panel prefix | Forms |
uploads_dir(url_prefix, dir) | stores file fields’ uploads in a directory and serves it at signed URLs that expire | Forms |
shell_assets(css, font) | adds the stylesheet, font and scripts | Assets |
layout(render) | frames the panel’s pages with your layout instead of the shell | The shell layout |
content_security_policy(..), without_content_security_policy() | replaces or drops the panel’s Content-Security-Policy | Security |
strict_transport_security(max_age) | sends HSTS on the panel’s responses | Security |
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
mdit 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,VieworEditon 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_nameand thesubtitletheirPanelUserreturns, such as an email. It opens the theme choice, a Profile link when the panel has a profile page, the entriesPanel::user_menu_itemadds, and Sign out. The Profile link follows the page into an area that holds it. A panel withAuth::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)
}
}
Sidebar
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.
Global search
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::declarereturns aPageDef, as a resource’s returns aResourceDef: 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::
- **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 ofStattiles.Stat::records::<R>(cx)counts whatR’s list would show the caller, throughscoped_query, and links to it; it isNonewhen 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 aChart, a line or bar chart over shared labels with aSeriesof 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 ofR’s records under its list’s own columns, or the onesRecordTable::columnnames by their field’s lens, with a link to the full list. It shows the records the list would, whichRecordTable::filternarrows, in theRecordTable::order_byorder, at mostRecordTable::limitof them. Each row links its View and Edit pages asR’s policy allows, and the columns hide whatR’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 askscan_listbefore it reads them, then reads them throughscoped_query, which keeps the tenant and the resource’s query but not its policy. - Layout.
PageDef::widget_columnssets how many columns the grid has on a wide screen, andWidgetDef::spanandWidgetDef::full_widthhow 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_columnssets its columns. The list’s sign-in and policy guard it, and it reruns with the list.list_query::<R>(cx)readsR’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(..))andPageFilter::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 throughscoped_queryorlist_query. A page that renders itself placespage_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")
}
}
brandnames 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_logoreplaces the logo while the page renders dark, so a wordmark stays legible on either background.faviconlinks 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 thetablo_themecookie and wins over this default. Under the system’s theme,tablo-ui’s script mirrors the system’s scheme intotablo_schemefor the server to render. Without the call the panel starts light.login_hintrenders 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:
| Theme | Looks like |
|---|---|
Theme::Jade, the default | the ruled sheet: a jade primary on cool neutrals, the page a white sheet inset in the sidebar’s frame |
Theme::Amber | the 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::Graphite | the 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::Iris | the 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::Ledger | Tablo’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.
| Token | Paints |
|---|---|
--background, --foreground | the page and its text |
--card, --card-foreground | cards, tables, dialogs and the sign-in and sign-up cards |
--popover, --popover-foreground | the option lists of selects and menus |
--muted, --muted-foreground | subdued surfaces and secondary text |
--primary, --primary-foreground | primary buttons and checked checkboxes |
--destructive, --destructive-foreground | delete buttons, errors, and the danger color |
--success, --warning, --info | the success, warning and info colors of badges and tinted cells |
--border | borders and dividers |
--input | the edges of inputs, selects, checkboxes and radios, a step stronger than --border |
--ring | focus rings |
--control | the face of inputs, selects and outline buttons |
--head, --rule, --rule-strong | the 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-foreground | the highlighter: hovered and selected rows, then text selection and <mark> |
--shadow-xs, --shadow-sm, --shadow-md, --shadow-lg | the shadows of the same names: menus and dialogs take --shadow-lg |
--shadow-card, --shadow-control, --shadow-button | the shadows of cards, inputs, and solid buttons |
--radius | the corners: rounded-lg, with rounded-md and rounded-sm 2px and 4px smaller and rounded-xl 4px larger |
--sidebar, --sidebar-foreground | the sidebar and its text |
--sidebar-primary, --sidebar-primary-foreground | the sidebar’s primary elements, --primary by default |
--sidebar-accent, --sidebar-accent-foreground | the hovered and active sidebar entry |
--sidebar-border, --sidebar-ring | the 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.