Laterite
Laterite is a content management framework for Rust: an admin panel from descriptors, themes edited in the admin, a media library, plugins, users and permissions, migrations and typed settings, on PostgreSQL, MySQL or SQLite.
cargo install laterite-cli
lat new
| Crate | Provides |
|---|---|
laterite-core | Config, errors, the database layer, migrations, modules. |
laterite-auth | Backend users, sessions, roles and permissions. |
laterite-admin | The admin router, list and form screens, settings. |
laterite-media | Content-addressed file storage. Optional. |
laterite-web | Static-site generation and page metadata. Optional. |
laterite-cli | The lat command. |
laterite-macros | The t!, tn! and tp! translation macros. |
| Section | Covers |
|---|---|
| Getting Started | Install, run, deploy and upgrade an application. |
| Configuration | Every key in the configuration files. |
| Admin Panel | Users, permissions, navigation, branding, settings and logs. |
| Forms, Lists, Elements | Screens from descriptors, and every field, column and filter type. |
| Plugins, Screens and Routes | Modules of your own and the screens they mount. |
| Database, Services, Media | Migrations, queries, events, sessions, search and files. |
| Themes and Markup | The site’s templates and the template language. |
| Reference | Behaviours, the command line, icons and the API documentation. |
Not in the framework today: mail, queues, a scheduler, a cache driver, an encryption service, multi-site.
Installation
lat new scaffolds a project, sets up the database and creates the first
administrator.
Install the CLI
cargo install laterite-cli
Requires stable Rust and one of PostgreSQL, MySQL/MariaDB or SQLite.
Create an application
lat new
cd acme
cargo run # or: lat serve
Open http://127.0.0.1:8080/admin and sign in.
lat new asks for:
| Prompt | Value |
|---|---|
| What are you building? | An application with an admin panel, or a static website (see Static Website). |
| Application name | Any text, such as Acme Blog. Its slug, acme-blog, names the crate, directory and database. |
| Where does the site’s content live? | Static website only: files you edit, a folder the admin writes, a folder the admin commits (git), or a database. |
| Site URL | Static website only: the origin canonical links use. |
| Display timezone | An IANA name; type to search. |
| Listen address | host:port. Default 127.0.0.1:8080. |
| Database | PostgreSQL, MySQL/MariaDB or SQLite, and its connection details. Offers to create the database. A folder or git site uses SQLite without asking. |
| First administrator | Username, email, password. Not asked for a site of files you edit. |
Every prompt has a flag: --static, --content, --url, --timezone, --listen, --admin with --admin-email, --admin-name and the password in LAT_NEW_ADMIN_PASSWORD. A script runs lat new without a terminal.
Serve
lat serve
lat serve --port 3000
lat serve --host 0.0.0.0
lat serve --listen 0.0.0.0:3000
Runs from anywhere inside the application. An override sets
<PREFIX>__SERVER__LISTEN; see Application and Server.
See what it generates
The layout, main.rs, the module file and the configuration files:
Directory Structure.
Set the brand
[app]
name = "Acme Blog"
Shown across the admin. Branding overrides it; with both
blank the brand is Laterite.
Check the setup
lat doctor
Verifies the configuration, the timezone, write access to storage/, the
database connection and the framework tables. Exits non-zero on any failure.
Manage administrators
lat admin create editor --email editor@acme.test --first-name Editor
lat admin reset-password editor
Both prompt for a password; --generate prints a strong one that must be
changed at first sign-in. Outside the
application, pass --database-url or set DATABASE_URL. A fresh install with
no accounts serves a first-run setup screen at /admin.
Static Website
lat new scaffolds a static website as a theme folder: pages, layouts,
partials, content and assets, with no database and no Rust project.
lat new "Acme" --static
cd acme
lat serve # http://127.0.0.1:8080, rebuilt on every change
lat theme build # dist/
lat new without --static asks first:
| Prompt | Value |
|---|---|
| What are you building? | An application with an admin panel, or a static website. |
| Where does the site’s content live? | In this folder as files you edit (--content files, what --static alone means); in this folder, edited in the admin (folder); in this folder, committed by the admin (git); in a database with the admin beside it (database). |
| Application name | Any text; its slug names the folder and the theme. |
| Site URL | The origin canonical links use. |
| Database, Build hook URL | For database: the connection, and the host’s hook (blank to set later). |
| First administrator | For every choice but files: username, email, password. |
lat new "Acme" --static --content git
cd acme
lat serve # the admin at http://127.0.0.1:8080/admin, the site beside it
lat make:resource article --field title:text --source content/articles --format markdown --git
git remote add origin git@github.com:acme/site.git
lat theme publish # push the commits the admin made
lat theme build # dist/, as the host does on push
A site whose content is edited in the admin is an application whose build is static: it carries the Cargo project, src/main.rs with the theme module, the framework’s own tables in storage/site.db (or the database named), and the theme folder. A folder or git site also carries its first plugin, plugins/site-plugin, with a post collection kept as records in files under content/posts/, the posts component the theme reads it through, and the pages /posts and /posts/:slug built per record. Folders named in theme.copy are served by lat serve as the build copies them. lat serve runs its admin; lat theme build renders dist/; lat theme publish pushes (git) or calls the build hook (database). Default https://<slug>.example.
See what it generates
acme/
├── config/default.toml # [app] name, url; [theme] folder, copy
├── themes/acme/
│ ├── theme.yaml
│ ├── layouts/default.htm
│ ├── pages/home.htm # url: /
│ ├── pages/about.htm # url: /about
│ ├── pages/404.htm
│ ├── partials/nav.htm
│ ├── content/intro.md
│ └── assets/css/site.css
├── build.sh # installs lat, runs the build
├── netlify.toml
└── README.md
A page carries its settings as front matter above the markup:
---
url: /about
layout: default
title: About
description: Who we are and what we do.
---
<h1>{{ this.page.title }}</h1>
<p>{{ this.page.description }}</p>
The settings and the template language are those of a theme in an application: Pages, Layouts and Partials, Content, Templating.
Set the config
[app]
name = "Acme"
url = "https://acme.example"
[server]
listen = "127.0.0.1:8080"
[theme]
folder = "themes/acme"
copy = ["static:static"]
| Key | Default | Meaning |
|---|---|---|
app.url | The origin canonical links use. | |
server.listen | 127.0.0.1:8080 | The preview’s address. |
theme.folder | The theme folder, relative to the project; its name is the theme’s code. | |
theme.copy | [] | Directories copied into the output, <src>:<dest>, relative to the project. A source absent on this machine is skipped with a note; a --copy flag’s is required. |
Preview
lat serve
lat serve --port 3000
lat theme serve --from themes/other
Every request rebuilds the site when a file under the folder changed; a template that does not compile shows its error in the browser.
Build and deploy
lat theme build
lat theme build --out public --base-url https://acme.example
lat theme build --from themes/other --copy docs/book:docs
| Flag | Default | Meaning |
|---|---|---|
--from <DIR> | theme.folder | The theme folder. |
--out <DIR> | dist | The output directory. |
--base-url <URL> | app.url | The origin canonical links use. |
--copy <SRC>:<DEST> | theme.copy | A directory copied into the output at <DEST>. Repeatable, added to the config’s. |
build.sh runs the same build on a host that starts from nothing:
cargo install laterite-cli --locked
lat theme build --out dist
netlify.toml points Netlify at it and serves dist/.
Choose where the content lives
[theme]
folder = "themes/acme"
source = "folder"
| Source | The theme is | Edited | Published |
|---|---|---|---|
database | the rows in [database] | in the admin | lat theme publish calls theme.publish.hook |
folder | the theme folder | in your editor, or in the admin, which writes the files | commit the folder |
git | the theme folder | in the admin, which commits every save | lat theme publish pushes |
| a module’s | its own | its own | its own |
folder and database are always available; git needs the theme-git feature:
lateritecmf = { version = "0.12", features = ["sqlite", "theme-git"] }
[theme]
folder = "themes/acme"
source = "git"
[theme.git]
remote = "origin"
branch = "main"
[theme.publish]
hook = "https://api.netlify.com/build_hooks/..."
| Key | Default | Meaning |
|---|---|---|
theme.source | database | The source by code. |
theme.git.remote, theme.git.branch | origin, main | Where publish pushes. |
theme.publish.hook | none | A URL lat theme publish posts to after the source published; the host rebuilds on it. |
A file-backed source is read in before every build, and every save in the admin is written back. The framework’s own tables (users, sessions, settings, logs) stay in [database].
Keep media with the site
[media]
folder = "public/media"
Uploads land in the folder, a git site commits each one, and the build writes every file and its variants under dist/storage/media/. See Admin configuration.
Edit from a laptop
cargo build --release
./target/release/acme admin
admin serves the application and opens the admin in the browser. With a folder or git source and records in files, every save lands in the checked-out repository; push it to publish.
| Command | Does |
|---|---|
acme or acme serve | Serves the admin and the site on server.listen. |
acme admin | The same, and opens /admin in the browser. |
acme build | Renders dist/. |
acme publish | Pushes, or calls the build hook. |
Add a plugin
lat plugin add https://github.com/rainmill/discovery-plugin
lat new "Acme" --static --plugin ../discovery-plugin
The first plugin gives the site a Cargo project (Cargo.toml, src/main.rs,
plugins/); lat serve and lat theme build run that binary from then on,
and the plugin takes part in the build. A plugin a static website can use
declares it in its manifest:
[package.metadata.laterite]
plugin = "rainmill.discovery"
static = true
A plugin without static = true is refused at install; one whose module
answers supports_static false stops the build, by name. A plugin’s
definitions live under plugins/<module id>/:
acme/
├── plugins/
│ ├── plugins.toml
│ └── rainmill.discovery/
│ ├── robots.yaml
│ └── sitemap.yaml
├── src/main.rs
└── Cargo.toml
# plugins/rainmill.discovery/robots.yaml
groups:
- agents: ["*"]
disallow: ["/drafts/"]
What each plugin reads is on its own page; the discovery plugin writes
robots.txt and a sitemap.xml of every page the build wrote.
Move to an application
cd themes && zip -r ../acme.zip acme && cd ..
lat new "Acme"
cd acme && lat theme import acme ../acme.zip
The folder is the theme’s export layout: the same files become the application’s theme. See Export and Import.
Directory Structure
lat new generates an application in this layout.
acme/
├── Cargo.toml
├── README.md
├── .gitignore
├── config/
│ ├── default.toml # committed defaults
│ └── local.toml # git-ignored; the database URL
├── plugins/
│ └── plugins.toml # the installed plugins
├── plugins-manifest/ # generated by `lat plugin sync`
├── src/
│ ├── main.rs
│ └── migrations/ # the application's module and its migrations
└── storage/ # runtime data; git-ignored
| Path | Holds |
|---|---|
Cargo.toml | The application crate and the workspace its plugins join. |
config/ | The layered configuration. See Application and Server. |
plugins/ | Installed plugin crates and the list that names them. See Installing Plugins. |
plugins-manifest/ | The generated crate that links the listed plugins. Never edited by hand. |
src/main.rs | The entry point. |
src/migrations/ | The application’s module and its migrations. See Migrations. |
storage/ | Files the application keeps while it runs. backend.storage moves it. |
Read main.rs
[dependencies]
lateritecmf = { version = "0.12", features = ["postgres"] }
laterite-core = "0.12"
plugins-manifest = { path = "plugins-manifest" }
use lateritecmf::prelude::*;
mod migrations;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
Bootstrap::new("config")
// Every plugin under plugins/, as listed in plugins/plugins.toml.
.modules(plugins_manifest::all())
.module(migrations::AppModule)
// .extend(|router, ctx| router.merge(my_api(ctx.db())))
.run()
.await
}
| Call | Description |
|---|---|
Bootstrap::new("config") | The configuration directory, relative to the working directory. |
.modules(..) | The installed plugins. |
.module(..) | The application’s own module. |
.extend(..) | Merges the application’s own routes onto the admin router. |
Read the module
src/migrations/mod.rs defines the application’s module:
use lateritecmf::prelude::*;
migration_set! {
module_id: "acme",
}
pub struct AppModule;
impl Module for AppModule {
fn id(&self) -> ModuleId {
ModuleId::new(MODULE_ID)
}
fn migrations(&self) -> MigrationSet {
migrations()
}
}
lat make:migration <description> adds a file to the directory and lists it in
the migration_set! block. The methods a module may add are in
Writing a Plugin.
Read the configuration
# config/default.toml
[app]
name = "Acme Blog"
env_prefix = "LAT"
# url = "https://acme.example"
[server]
listen = "127.0.0.1:8080"
[backend]
timezone = "UTC"
secure_cookie = false
# path = "/admin"
# config/local.toml
[database]
url = "postgres://localhost/acme"
Every key is in Configuration.
Development Workflow
Two local conveniences: a .test domain per application and a rebuild that
keeps the browser connected.
Use a local domain
lat domain routes every host under a reserved .test TLD to loopback. macOS,
built on dnsmasq.
brew install dnsmasq
lat domain setup
setup writes a dnsmasq wildcard rule and /etc/resolver/test, prompting
for sudo. It is idempotent.
| Flag | Description |
|---|---|
--dry-run | Print the plan and change nothing. |
--tld <name> | Use a different reserved TLD. |
Open an application by name
lat serve --port 8080
# http://acme.test:8080/admin
Set app.url to match:
[app]
url = "http://acme.test:8080"
The port stays in the URL. HTTPS on the bare name is a reverse proxy’s job.
Status and teardown
lat domain status
lat domain teardown
teardown removes only what lat domain created. A .test managed by another
tool is detected: setup adds nothing and teardown leaves it alone.
Reload on change
systemfd holds the port and watchexec rebuilds on change; the browser
reconnects after every edit.
cargo install systemfd
brew install watchexec # or cargo install watchexec-cli
Reuse the passed socket
Add listenfd and take the socket in
main:
use listenfd::ListenFd;
use tokio::net::TcpListener;
let listener = match ListenFd::from_env().take_tcp_listener(0)? {
Some(std_listener) => {
std_listener.set_nonblocking(true)?;
TcpListener::from_std(std_listener)?
}
None => TcpListener::bind("127.0.0.1:8080").await?,
};
axum::serve(listener, app).await?;
None is the normal path: cargo run and production bind directly.
Run the loop
systemfd --no-pid -s http::8080 -- \
watchexec -r -e rs,html,css,toml -- \
cargo run -p acme
.html and .css are watched too: templates and the stylesheet are compiled
in. As a justfile recipe:
dev:
systemfd --no-pid -s http::8080 -- \
watchexec -r -e rs,html,css,toml -- \
cargo run -p acme
See errors as you type
cargo install bacon # or brew install bacon
bacon clippy
Deployment
Running an application in production: a release binary, the files beside it, secrets from the environment, and a reverse proxy in front.
Build the binary
cargo build --release
# target/release/acme
Run it from a directory holding config/.
Ship the files
| Path | Description |
|---|---|
acme | The release binary. Plugins are compiled into it; nothing of plugins/ ships. |
config/default.toml | The committed defaults. |
config/production.toml | Optional. Read when APP_ENV=production. |
storage/ | Writable by the process. Empty on the first start. |
config/local.toml stays on the development machine. Secrets travel as
environment variables.
Set secrets in the environment
export APP_ENV=production
export LAT__DATABASE__URL="postgres://acme:secret@db.internal/acme"
export LAT__APP__KEY="$(lat key generate --print | head -1)"
./acme
| Variable | Sets |
|---|---|
APP_ENV | Which config/<APP_ENV>.toml layer is read. Default development. |
<PREFIX>__DATABASE__URL | database.url. |
<PREFIX>__APP__KEY | app.key, the key everything is sealed and signed under. Set it in production; several instances share it. See Encryption and Signing. |
<PREFIX>__SECTION__KEY | Any other key. The prefix is app.env_prefix, LAT by default. |
Sit behind a proxy
# config/production.toml
[app]
url = "https://acme.example"
[server]
listen = "127.0.0.1:8080"
[backend]
secure_cookie = true
trusted_proxies = ["127.0.0.1/32"]
| Key | Description |
|---|---|
app.url | The public origin absolute links build on. |
backend.secure_cookie | Sets the Secure flag on cookies. true behind HTTPS. |
backend.trusted_proxies | CIDR ranges whose X-Forwarded-For is read. The proxy’s own network. |
server {
listen 443 ssl;
server_name acme.example;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
Gate the deploy
lat doctor
| Check | Passes when |
|---|---|
| Configuration loads | Every layer parses and database.url is present. |
| Timezone is valid | backend.timezone is an IANA name. |
storage/ is writable | The process can write the application’s storage/. |
| Database is reachable | A connection opens. |
| Tables exist | The framework’s tables are migrated. |
| plugins-manifest is in sync | The list and the generated crate agree. |
| Descriptor files parse | Every YAML descriptor loads. |
Exits non-zero on any failure. Run it from the application directory, or pass
--database-url.
Recover access
lat admin create ops --email ops@acme.example --first-name Ops --generate
lat admin reset-password editor --generate
lat admin unlock editor
lat admin purge
| Command | Description |
|---|---|
create | A new superuser. --generate prints a strong password. |
reset-password | A new password for an existing user. |
unlock | Clears a user’s failed sign-in lockout. |
purge | Removes expired sessions and stay-signed-in credentials. |
Outside the application directory, pass --database-url or set DATABASE_URL.
Upgrading
Moving an application to a newer framework version.
Read the changelog
The crates release together under one version. Read the version’s section of
CHANGELOG.md
before bumping.
| Bump | Before 1.0 |
|---|---|
Patch, 0.9.19 to 0.9.20 | Additive or a fix. No code changes. |
Minor, 0.11 to 0.12 | May break. The section lists what moved. |
Bump the requirements
Every laterite-* and lateritecmf requirement moves together.
# Cargo.toml
[workspace.dependencies]
lateritecmf = { version = "0.12", features = ["postgres"] }
laterite-core = "0.12"
laterite-admin = "0.12"
# plugins/<folder>/Cargo.toml, for each plugin the application owns
[dependencies]
laterite-core = "0.12"
laterite-admin = "0.12"
| Crate | Description |
|---|---|
lateritecmf | The umbrella an application depends on. |
laterite-core | Configuration, migrations, modules, queries. |
laterite-admin | The admin panel. |
laterite-auth | Sign-in, sessions, permissions. |
laterite-media | The media library. |
laterite-web | Themes and public pages. |
laterite-macros | The translation-string macros. |
laterite-cli | The lat command. |
cargo install laterite-cli
cargo update
cargo build --release
A patch needs cargo update alone; the requirement already admits it.
Run the migrations
lat serve
Starting the application applies the framework’s new migrations, then the application’s and the plugins’.
Check the result
lat doctor
Third-Party Notices
A built binary carries the licence notices of everything compiled into it.
Distribute source or a crate
Nothing to do: licence files travel inside each package.
Distribute a binary
Generate a notice with
cargo about and ship it
beside the binary:
cargo install cargo-about
cargo about init # writes about.toml and about.hbs
cargo about generate about.hbs > NOTICE.html
It reads every dependency’s NOTICE, LICENSE and COPYING, Laterite’s
bundled fonts and icons included.
What Laterite bundles
| Work | Licence |
|---|---|
| IBM Plex Sans, IBM Plex Mono | SIL Open Font License 1.1 |
| Space Grotesk | SIL Open Font License 1.1 |
| Lucide, a subset | ISC, with an MIT annex for icons derived from Feather |
| htmx | Zero-Clause BSD |
Full texts: crates/admin/NOTICE.
Application and Server
Configuration is layered: one build runs across environments without code
changes. This page covers the layers, [app] and [server].
Layer the files
Later layers override earlier ones.
| Layer | Source |
|---|---|
| 1 | default.toml. Required. |
| 2 | <APP_ENV>.toml. Optional. APP_ENV defaults to development. |
| 3 | local.toml. Optional; keep it out of version control. |
| 4 | <PREFIX>__SECTION__KEY environment variables, e.g. LAT__DATABASE__URL. The prefix is LAT unless app.env_prefix names another. |
| Section | Page |
|---|---|
[database] | Database |
[backend] | Admin |
[auth] | Authentication |
Set [app] and [server]
[app]
name = "Acme Blog" # baseline admin brand
env_prefix = "LAT" # prefix of the overriding environment variables
locale = "en" # default admin language
debug = false # error pages show the cause
# url = "https://acme.example" # public base URL; derived from listen when unset
[server]
listen = "127.0.0.1:8080"
| Key | Description |
|---|---|
app.name | The application name, the baseline admin brand. Branding overrides it. Default Laterite. |
app.url | The public base URL absolute links build on, scheme and host with any port. Derived from server.listen when unset. |
app.locale | Default admin UI language, a BCP 47 tag. Default en. See Localization. |
app.debug | Error pages include the cause. Off by default. See Errors and Logging. |
app.env_prefix | The prefix of the overriding environment variables. Default LAT. |
app.key | The application key, id:<base64 of 32 bytes>; lat key generate writes one. See Encryption and Signing. |
app.previous_keys | Keys retired by a rotation, each id:<base64>, read but never written with. |
server.listen | The host:port to bind. Default 127.0.0.1:8080. lat serve --host, --port and --listen override it. |
Set [cache]
[cache]
store = "auto" # auto | null | memory | redis
memory_mib = 64
poll_seconds = 2
# url = "redis://127.0.0.1:6379/0"
| Key | Description |
|---|---|
cache.store | auto is null while app.debug is on and memory otherwise. See Cache. |
cache.memory_mib | The memory store’s capacity. Default 64. |
cache.poll_seconds | How often a process reads the other processes’ invalidations; 0 for a single process. Default 2. |
cache.url | The Redis URL for the redis store. |
cache.prefix | The prefix of every Redis key. Default laterite. |
Set [queue]
[queue]
store = "auto" # auto | database | redis
mode = "worker" # worker | external | inline
workers = 2
queues = ["default"]
retry_after_seconds = 90
| Key | Description |
|---|---|
queue.store | Where jobs wait; auto is database. See Queue. |
queue.mode | worker in the application process, external for queue work alone, inline to run a job as it is pushed. |
queue.workers | Workers per process in worker mode. Default 2. |
queue.queues | The queues taken from, in priority order. Default ["default"]. |
queue.retry_after_seconds | When a claimed job counts as abandoned. Default 90. |
queue.poll_seconds | An idle worker’s wait. Default 1. |
Set [schedule]
[schedule]
mode = "ticker" # ticker | external | off
| Key | Description |
|---|---|
schedule.mode | ticker in the application process, external for schedule run alone, off for none. See Scheduler. |
Set [mail]
[mail]
driver = "smtp" # smtp | log | stub
from = "Acme <no-reply@acme.example>"
[mail.smtp]
host = "smtp.acme.example"
port = 587
encryption = "starttls"
username = ""
password = ""
| Key | Description |
|---|---|
mail.driver | smtp, log or stub; the Mail settings screen lays over it. See Mail. |
mail.from | The sender, Name <address>. |
mail.to | A development override for every recipient. |
mail.smtp.* | host, port, encryption (starttls, tls, none), username, password, timeout_seconds. |
Set [theme]
[theme]
folder = "themes/acme"
copy = ["static:static"]
| Key | Default | Meaning |
|---|---|---|
folder | none | A static website’s theme folder, relative to the project. Set, lat serve previews it and lat theme build renders it. See Static Website. |
copy | [] | Directories copied into the build output, <src>:<dest>, relative to the project; one absent on this machine is skipped with a note. |
source | database | Where the theme lives: database, folder, git (feature theme-git), or a code a module registered. |
git.remote, git.branch | origin, main | Where the git source pushes on publish. |
publish.hook | none | A build hook URL publish posts to. |
Mount a module’s screens
A module’s screens namespace under its identity: acme.places
contributing /nodes serves /admin/acme/places/nodes. A module may
declare a shorter base; backend.paths has the last word.
Locate the application from lat
lat walks up from the current directory to the nearest config/default.toml
and reads the application’s prefix from it. lat admin takes the database URL
from --database-url, then DATABASE_URL, then database.url.
Find what is not configured here
| Setting | Where |
|---|---|
| Branding: name, colour-mode default, logo | Branding |
| Preferences: a user’s own timezone | Preferences. See Dates and Timezones. |
Database
[database] names the connection.
[database]
url = "postgres://localhost/acme_dev"
max_connections = 10 # optional
acquire_timeout_secs = 5 # optional
| Key | Description |
|---|---|
url | The connection URL. Required. |
max_connections | The pool ceiling. Default 10. |
acquire_timeout_secs | Seconds to wait for a pooled connection. Default 5. |
Choose the driver
| Database | URL | Feature |
|---|---|---|
| PostgreSQL | postgres://user:pass@host/acme | postgres |
| MySQL / MariaDB | mysql://user:pass@host/acme | mysql |
| SQLite | sqlite://storage/database.db?mode=rwc | sqlite |
[dependencies]
lateritecmf = { version = "0.12", features = ["postgres"] }
Keep the URL out of version control
# config/local.toml, git-ignored
[database]
url = "postgres://localhost/acme_dev"
LAT__DATABASE__URL="postgres://acme:secret@db.internal/acme" ./acme
Give lat the URL
lat admin list --database-url postgres://localhost/acme_dev
DATABASE_URL=postgres://localhost/acme_dev lat admin list
| Source | Order |
|---|---|
--database-url | First. |
DATABASE_URL | Second. |
database.url of the application found from the current directory upward | Last. |
Admin
[backend] configures the admin panel. Every key is optional.
[backend]
secure_cookie = false # true behind HTTPS
timezone = "UTC" # default display timezone, IANA name
path = "/admin" # where the admin mounts
trusted_proxies = [] # CIDR ranges whose X-Forwarded-For is believed
storage = "storage" # where files the admin keeps go
secret = "a-long-random-string" # signs timed URLs
skin = "standard"
upload_extensions = []
origin_check_except = ["/webhooks/*"]
[backend.order]
"backend.nav" = ["dashboard", "acme.shop", "media", "settings"]
[backend.menu]
"backend.access_log" = { in = "backend.nav", slot = "tools" }
[backend.paths]
"acme.places" = "/places" # a whole module's screens
"acme.places/nodes" = "/places" # one screen; the more specific key wins
Set the keys
| Key | Description |
|---|---|
secure_cookie | Sets the Secure flag on cookies and sends Strict-Transport-Security (one year, subdomains included). true behind HTTPS. |
timezone | Default display timezone until a user picks their own. See Dates and Timezones. |
path | URL path the admin mounts under. |
trusted_proxies | CIDR ranges. X-Forwarded-For is read only from a peer inside one. Empty records the peer address. |
paths | Remounts a module’s screens, or one screen, at another path. Two claims on one path abort the boot. |
upload_extensions | The file extensions an upload may carry, lowercased. Empty applies the default list (images, documents, audio, video, fonts, archives). See Media Library. |
origin_check_except | Paths a POST from another site may reach: an exact path, or a prefix ending in *. Only for endpoints that authenticate each request themselves. See Public Routes. |
skin | The admin skin by code: standard (default), compact, or one a module registered. See Skins. |
storage | The directory files the admin keeps go under, relative to the working directory unless absolute. Uploaded import files go to private beneath it. |
Keep the media library in the project
[media]
folder = "public/media"
| Key | Default | Meaning |
|---|---|---|
media.folder | none | A folder of the project the library stores its files in. Unset, the library uses <backend.storage>/media. With [theme] source = "git", every stored or removed file is committed. |
A static build writes every file and variant under dist/storage/media/, at the paths the pages link to.
order | Arrangement overrides by hierarchy: "backend.nav", "backend.nav.<section>", "backend.settings" or a plugin’s own, each a list of keys in the wanted order. See Navigation.
menu | Entries moved out of their home, keyed by entry: { in, slot, order, category }. See Navigation.
secret | The key timed URLs are signed with (a private file’s). Set it when several instances share one database.
Authentication
[auth] sets session lifetimes, sign-in lockouts and the password policy.
Every key is optional.
[auth]
session_idle_timeout_secs = 7200 # 2h
session_absolute_timeout_secs = 43200 # 12h
remember_duration_secs = 1209600 # 14d
max_failures = 5
max_failures_per_address = 20
failure_window_secs = 900
access_log_retention_days = 365
[auth.password_policy]
min_length = 8
Set the keys
| Key | Description |
|---|---|
session_idle_timeout_secs | Quiet time before a session ends, from the last request. Default 7200. |
session_absolute_timeout_secs | Ceiling from login, never extended. Default 43200. The earlier name session_ttl_secs is still read. |
remember_duration_secs | How long an unused “stay signed in” credential lasts, from its last use. Default 1209600. |
max_failures | Failed sign-ins from one address for one username before that address is locked out of it. Default 5. |
max_failures_per_address | Failed sign-ins from one address, any username, before the address is locked out. Default 20. |
failure_window_secs | Window the failures are counted over. Default 900. |
access_log_retention_days | Days of the access log the hourly purge keeps. Default 365; 0 keeps every row. |
password_policy.min_length | The shortest password accepted, wherever one is set. Default 8. |
Clear a lockout
lat admin unlock editor
Dates and Timezones
Timestamps are stored in UTC and converted to a display timezone when rendered.
Display a timestamp
use laterite_admin::list::ListColumn;
ListColumn::new("created_at", "Created").datetime();
ListColumn::new("published_on", "Published").date();
ListColumn::new("is_active", "Active").yes_no();
| Kind | Rendered as |
|---|---|
text | The stored value. Default. |
datetime | 14 Aug 2026, 15:53, in the viewer’s timezone. |
date | The date, in the viewer’s timezone. |
time | The time, in the viewer’s timezone. |
yes_no | Yes or No. |
A value that does not parse is shown as stored.
Choose the timezone
Resolved per request:
- The user’s own preference, set under Preferences.
- Otherwise
backend.timezone, an IANA name such asAsia/Kolkata. Defaults toUTC.
“Use the deployment default” in Preferences clears the user’s choice.
Errors and Logging
Admin handlers return Result<_, laterite_admin::AdminError>; the log follows
RUST_LOG.
| Variant | Status | Page |
|---|---|---|
NotFound | 404 | Not found |
Forbidden | 403 | Forbidden |
Internal(_) | 500 | Something went wrong |
Map a domain error
async fn edit(state: &AdminState, id: &str) -> Result<Response, AdminError> {
let row = fetch(state, id)
.await? // CoreError::NotFound -> 404, DB error -> 500
.ok_or(AdminError::NotFound)?; // a missing row -> 404
Ok(render(view(row)))
}
| From | To |
|---|---|
CoreError::NotFound | 404 |
CoreError::Forbidden, CoreError::Unauthorized | 403 |
AuthError | Through CoreError, the same mapping |
| A database error, a render failure, a panic | 500 |
An unmatched admin URL renders the 404 page.
Show the cause in development
[app]
debug = true # off by default
A 500 logs its cause through tracing::error! in every mode. With debug on,
the page shows it too. See Application and Server.
Configure logging
RUST_LOG=debug lat serve
RUST_LOG=info,laterite_admin=debug ./acme
| Variable | Description |
|---|---|
RUST_LOG | A tracing filter directive. Unset, the filter is info,sqlx=warn. |
An application that installs its own tracing subscriber before serve()
keeps it.
Refuse a submission
A refused submission is not an AdminError: it answers 422 with the form
re-rendered. See Validation.
Users and Roles
An operator is a person who signs in to the admin. Accounts are managed under
Settings → Users → Administrators, gated by backend.manage_users; roles
and what each holds are on Permissions. Every action on an
account is on the audit log, named after the account it touched.
Create an operator from the command line
lat admin create editor --email editor@acme.test --first-name Editor --generate
lat admin reset-password editor --generate
lat admin list
--generate prints a strong password and marks it temporary; a typed or
prompted password is the operator’s own.
Create an operator from code
use laterite_auth::NewOperator;
use laterite_core::Actor;
let id = auth
.create_operator(
NewOperator {
username: "editor",
email: "editor@acme.test",
first_name: "Editor",
last_name: None,
password: &laterite_auth::password::generate(),
timezone: None,
},
&Actor::user(admin.id, &admin.username),
)
.await?;
auth.require_password_change(id).await?;
let temporary = auth.reset_operator_password(id, &actor).await?;
auth.unlock("editor").await?;
| Call | Description |
|---|---|
create_operator(new, actor) | A new account; the id is returned. |
require_password_change(id) | Marks the password temporary; the account replaces it at its next sign-in. |
reset_operator_password(id, actor) | A new temporary password, returned once; every device is signed out. |
unlock(username) | Clears a sign-in lockout. |
create_superuser | A superuser, the same way; first-run setup and lat admin create use it. |
Invite an operator and reset a password
laterite.auth::invite name, username, link, expires
laterite.auth::reset name, username, link, expires
| Page | Does |
|---|---|
/admin/users/new | Creates the account, shows the temporary password once, and mails laterite.auth::invite with a link to set a password; the link works for seven days. |
/admin/forgot | Linked from the sign-in page. Takes a username or email address and mails laterite.auth::reset with a link that works for one hour; the page says the same whether or not the account exists, and one address may ask five times in fifteen minutes. |
/admin/set-password/<token> | Opened from either link: a new password, checked against the password policy, then the sign-in page. |
Both templates are edited under Settings → System → Mail Templates. The mail goes through the configured transport; with the log driver it sits in the Mail Log.
Groups
A group is a named set of accounts, for addressing people together. It grants
no permissions. Groups are managed under Settings → Users → Groups, gated
by backend.manage_groups, and ticked on an account’s page.
use laterite_auth::store;
let staff = store::create_group(&db, "staff", "Staff", Some("Everyone"), true).await?;
store::join_group(&db, user_id, staff).await?;
store::set_user_groups(&db, user_id, &[staff]).await?;
let mine = store::user_group_ids(&db, user_id).await?;
let members = store::group_member_ids(&db, staff).await?;
let id = store::group_id_by_code(&db, "staff").await?;
| Call | Description |
|---|---|
create_group(db, code, name, description, default) | A new group; the id is returned. The code is stored lowercase. |
list_groups(db) | Every group, by name. |
group_id_by_code(db, code) | The id of the group with that code. |
join_group(db, user, group) | Adds one account. |
join_everyone(db, group) | Adds every account. |
set_user_groups(db, user, groups) | Replaces an account’s groups. |
user_group_ids(db, user) | The groups an account is in. |
group_member_ids(db, group) | The accounts in a group. |
A group whose New accounts join this group is on is given to every account created afterwards; creating one on the Groups screen also adds every existing account.
Permissions
A permission is a dotted string such as posts.approve. A descriptor declares
the one a screen requires; the framework checks it against the operator’s
roles.
Register permissions
use laterite_admin::{Permission, ROLE_EDITOR};
use laterite_core::t;
registry.add_permission(
Permission::new("acme.publish_pages", t!("Publish pages"), t!("Content"))
.roles([ROLE_EDITOR]),
);
Registered permissions appear in the role editor under their group. Only a
registered permission can be granted.
Rename a permission
Permission::new("acme.posts", t!("Manage posts"), t!("Content"))
.renamed_from(["acme.manage.posts"])
At the next start every role and per-user override holding the old code is rewritten to the new one. Two permissions claiming one old code, or an old code still registered, abort the start.
Place a permission in a built-in role
| Role | Holds |
|---|---|
ROLE_ADMIN, Administrator | Every permission that names no role, plus any naming it. The first operator holds it. |
ROLE_EDITOR, Editor | Only the permissions that name it. Empty until your application registers some. |
Permission::roles names the roles that hold a permission by default. Naming
none means the administrator alone. Neither role is editable: duplicate one to
make it yours.
Gate a screen
use laterite_admin::Resource;
registry.add_resource(
Resource::new("/pages", "Pages", pages_list_config())
.form(pages_form_config())
.permission("acme.manage_pages"),
);
| Where | Effect |
|---|---|
Resource::permission | Every route the resource mounts: 403 without the grant, the login screen when signed out. Unset leaves it open to any operator. |
SettingsItem::permission | Hides the item from the settings menu and refuses its form. |
ScreenReg::new(path, permission, ..) | Required. Enforced before the handler runs. |
ToolbarButton::require | The button is not rendered without the grant. |
Shell::allows(code) | In a module’s own handler: whether to show a control or answer 403. |
Resource::create_permission, update_permission, delete_permission | One write each, beside Resource::permission (below). |
Gate each write
# descriptors/posts.yaml
permission: acme.posts
permissions:
create: acme.posts.create
update: acme.posts.update
delete: acme.posts.delete
Resource::new("/posts", "Posts", list)
.form(form)
.permission("acme.posts")
.create_permission("acme.posts.create")
.update_permission("acme.posts.update")
.delete_permission("acme.posts.delete")
| Key | Asked for by | Without it |
|---|---|---|
create | The New form and its save | No New button; 403 |
update | A save, an editable cell, a move or reorder, a related record’s change | The form opens read-only, with no Save; the section has no New; 403 |
delete | Delete, restore, delete permanently | No row selection or Delete; 403 |
An operator needs permission and the key’s grant. A key left out asks for
permission alone. A key naming a permission no module registers
aborts the start.
Match a grant
| Grant | Covers |
|---|---|
posts.approve | Exactly posts.approve. |
posts.* | posts.approve, posts.tags.create; not the bare posts. |
* | Everything. |
A superuser passes every check.
Resolve for one operator
- A superuser: allowed.
- The operator’s own override for that permission: Deny refuses, Allow grants.
- Otherwise the roles decide.
Roles and overrides are both set per user on the Administrators screen; Inherit is the default.
Grant a built-in permission
| Permission | Grants |
|---|---|
backend.manage_users | The backend users list and per-user overrides. |
backend.manage_roles | The roles list and the role editor. |
backend.manage_groups | The groups list, a group’s form and its members. |
backend.manage_plugins | The plugins screen. |
backend.view_audit_log | The audit log. |
backend.view_access_log | The access log. |
backend.view_request_log | The request log. |
Navigation
A resource and a screen each add their own menu entry. A module adds sections and extra entries through its registry.
Add an entry
# descriptors/posts.yaml
menu: { under: acme.content, icon: file-text, order: 2 }
registry.add_nav(NavItem::new("acme.reports", "Reports", "/reports").permission("acme.reports"));
Resource::new("/posts", "Posts", list)
.permission("acme.posts")
.menu(Placement::new().under("acme.content").icon("file-text").order(2))
ScreenReg::new("/reports", "acme.reports", Arc::new(ReportsScreen))
.in_menu("Reports")
.menu(Placement::new().under("acme.content"))
menu key | Default | Description |
|---|---|---|
under | the top bar | The key of the section the entry sits under. |
icon | none | An icon name from the icon set. |
slot | application | The band the entry belongs to (see below). |
order | 0 | Sorts among siblings of the band, lowest first; equal orders sort by label. |
after, before | none | Sits right after or before the sibling with that key, whatever the bands say. A resource’s key is resource: and its path (resource:/posts), a screen’s screen: and its path, a contributed item’s its own. |
in_settings | none | A Settings category heading (System): the entry is listed in Settings under it, with no menu entry. |
description | none | The line under the label in Settings. |
menu: false | Mounts the routes with no menu entry. |
| Slot | Value | Holds |
|---|---|---|
home | 0 | The dashboard. |
content | 100 | What the site publishes. |
media | 200 | The media library. |
application | 500 | The application’s own screens: the default. |
people | 700 | Accounts and roles. |
tools | 800 | Reports, logs and tools. |
system | 900 | Settings. |
last | i32::MAX | After everything. |
NavItem | Description |
|---|---|
NavItem::new(key, label, path) | An entry leading to path under the admin mount. |
NavItem::section(key, label) | A tab holding entries; it leads to the first one the operator may open. |
.icon(name), .order(n), .after(key), .before(key), .under(key), .permission(code) | As the menu keys above; permission hides the entry from an operator without it. |
.in_settings(category) | Renders the entry in Settings under category (see below). |
.description(text) | The line under the label in Settings. |
A resource’s entry carries the resource’s permission, a screen’s its own. A
duplicate key, under naming a key nobody declared, or after and before
naming no sibling, aborts the start.
Add a section
registry.add_nav(NavItem::section("acme.content", "Content").icon("folder").order(10));
Resource::new("/pages", "Pages", list)
.menu(Placement::new().under("acme.content").order(1))
A section is a tab in the top bar. An operator sees only the entries they may open; a section with none left is not shown. Dashboard and Settings are always first and last.
Place a section in Settings
registry.add_nav(
NavItem::section("acme.shop", t!("Shop"))
.icon("store")
.description(t!("Products, orders and invoices."))
.slot(slot::SYSTEM)
.in_settings(t!("Shop")),
);
# descriptors/products.yaml
menu: { under: acme.shop, order: 1 }
# descriptors/orders.yaml
menu: { under: acme.shop, order: 2 }
| Placed | Renders |
|---|---|
| A section | One settings item linking to its first entry; each entry’s list shows the entries as tabs. |
| An entry | A settings item linking to its page. |
| A tab the operator lacks the permission for | Left out of the tabs. |
A deployment’s [backend.menu] move places a section the same way, or puts a
module’s settings section back in the top bar with its entries in the sidebar:
[backend.menu]
"acme.shop" = { in = "backend.settings", category = "Shop" }
"rainmill.pdf" = { in = "backend.nav" }
Order a hierarchy
[backend.order]
"backend.nav" = ["dashboard", "acme.shop", "media", "settings"]
"backend.nav.acme.content" = ["resource:/pages", "resource:/posts"]
"backend.settings" = ["backend.branding", "web.themes"]
| Hierarchy | Keys | Pinned |
|---|---|---|
backend.nav | The top bar’s entries. | dashboard first, settings last. |
backend.nav.<section> | A section’s entries. | none |
backend.settings | Settings items by code. | none |
A key left out keeps its arrangement after the listed ones; a key that is no entry is skipped.
A hierarchy of your own takes the same [backend.order] key:
use laterite_core::arrange::{arrange, Arranged, Hierarchy, Overrides, Policy, Position, slot};
let widgets = arrange(
&Hierarchy::new("acme.dashboard").policy(Policy::Fixed),
widgets,
Overrides { deployment: config.order.get("acme.dashboard").map(Vec::as_slice), operator: None },
)?;
Hierarchy builder | Description |
|---|---|
new(key) | The key [backend.order] names. |
policy(Policy::Fixed) | Renders the declared arrangement; overrides are logged and ignored. Adjustable is the default. |
operator_adjustable() | Lets an operator’s preference rearrange it too. |
pin_first(key), pin_last(key) | Keys that hold the ends whatever anyone says. |
Move an entry
[backend.menu]
"backend.access_log" = { in = "backend.nav", slot = "tools" }
"resource:/orders" = { in = "backend.settings", category = "Shop", order = 5 }
"screen:/reports" = { in = "backend.nav.acme.content" }
[backend.menu] key | Meaning |
|---|---|
| The entry | A menu key (resource:/orders, screen:/reports, a contributed item’s key) or a settings item’s code. |
in | backend.nav, backend.nav.<section> or backend.settings. |
slot, order | The band and order there; the entry’s own when left out. |
category | The settings heading; the band’s name when left out. |
A moved entry keeps its label, icon, permission and target: a resource moved into settings opens at its own path with the settings sidebar beside it, and a settings item moved into the top bar is a tab. A section moved into settings is one item with its entries as tabs.
Register a palette source
# descriptors/posts.yaml
palette: acme.posttitles
Resource::new("/posts", "Posts", list).palette("acme.posttitles")
| Key | Description |
|---|---|
palette | A registered picker source. The command palette (Ctrl+K, Cmd+K) finds this resource’s records through it and opens each at its edit page. Absent keeps the records out. |
Branding
Settings › Branding, saved by a user with backend.manage_branding. A blank
name keeps app.name.
Set the fields
| Field | Takes | Effect |
|---|---|---|
| Application name | text | the brand in the top bar, drawer, sign-in page and titles; blank keeps app.name |
| Logo | a library image | shown in place of the mark |
| Navigation logo | a library image | shown in the top bar and drawer; blank uses the logo |
| Browser icon | a library image | the tab icon |
| Accent colour | #rrggbb | --accent, its pressed shades and tints, and link colours |
| Colour mode | auto, light, dark | what a user sees before choosing their own |
| Sign-in prompt | text | the line above the sign-in form |
| Sign-in tagline | text | the line on the panel beside the form |
| Sign-in background | a library image | behind that panel |
| Show the panel | on, off | off leaves the form alone, centred |
| Custom stylesheet | CSS | added to every admin page; @import, scripts and closing tags are removed |
Each image is a public media field: the picker takes public files alone. See Storage Disks.
Skins
A skin is a stylesheet layered after the framework’s own, selected per
deployment by backend.skin.
Select a skin
# config/default.toml
[backend]
skin = "compact"
| Code | Ships with | Stylesheet |
|---|---|---|
standard | the framework | none |
compact | the framework | tighter spacing, smaller controls, a narrower sidebar |
Contribute a skin
use laterite_admin::skin::Skin;
use laterite_admin::{AdminAsset, AdminRegistry};
use laterite_core::t;
fn register(registry: &mut laterite_core::Registry) {
registry.add_asset(
"acme/dense.css",
AdminAsset::css(include_bytes!("../assets/dense.css")),
);
registry.add_skin(Skin {
code: "acme.dense",
label: t!("Dense"),
stylesheet: Some("acme/dense.css"),
});
}
/* assets/dense.css */
:root[data-lat-skin="acme.dense"] {
--card-pad: 10px;
--control-h: 32px;
--sidebar-w: 220px;
}
[data-lat-skin="acme.dense"] .lat-table td {
padding: 6px 10px;
}
| Field | Value |
|---|---|
code | Selected by backend.skin. A module’s carries its vendor: acme.dense. |
label | The skin’s name. |
stylesheet | The asset key to load after laterite.css, or None. |
add_asset(key, asset) serves a compiled-in file at {admin}/assets/{key},
content-named and cached for a year.
| Constructor | Media type |
|---|---|
AdminAsset::css(bytes) | text/css |
AdminAsset::js(bytes) | text/javascript |
AdminAsset::new(mime, bytes) | as given |
Set the tokens
The document element carries data-lat-skin="<code>" on every admin page,
the sign-in page and the setup page. A skin’s rules key on it.
:root[data-lat-skin="acme.dense"] {
--topnav-h: 54px;
--sidebar-w: 230px;
--side-panel-w: 300px;
--page-gutter: 20px;
--card-pad: 14px;
--control-h: 34px;
--control-h-sm: 28px;
--control-h-lg: 40px;
--radius-control: 6px;
--radius-card: 6px;
}
| Token | Sets |
|---|---|
--topnav-h | Top bar height |
--sidebar-w | The sidebar’s width, the same open or closed; a longer title ends in an ellipsis, a description after two lines |
--side-panel-w | Context side panel width |
--page-gutter | Page padding |
--card-pad | Card padding |
--control-h, --control-h-sm, --control-h-lg | Input and button heights |
--radius-control, --radius-card | Corner radii |
The brand’s accent and custom stylesheet load after the skin.
An unknown backend.skin code, a skin naming an unregistered stylesheet key,
a duplicate skin code, or an asset key already served all abort the start.
Dashboard Widgets
A dashboard widget is a card a module registers for the home dashboard, a board each operator arranges for themselves.
Write a widget
use laterite_admin::widget::{Size, Widget, WidgetCx, WidgetReg};
use laterite_admin::{html::Markup, AdminRegistry};
use laterite_core::arrange::{slot, Position};
use laterite_core::{t, Text};
use std::sync::Arc;
struct Sales;
#[laterite_core::strata::async_trait]
impl Widget for Sales {
fn code(&self) -> &str {
"acme.sales"
}
fn label(&self) -> Text {
t!("Sales today")
}
fn description(&self) -> Option<Text> {
Some(t!("Orders and revenue since midnight."))
}
fn permission(&self) -> Option<&str> {
Some("acme.view_sales")
}
fn size(&self) -> Size {
Size::Third
}
fn refresh(&self) -> Option<u32> {
Some(30)
}
async fn render(&self, cx: &WidgetCx<'_>) -> Result<Markup, String> {
let count = acme::orders::today(cx.db()).await.map_err(|e| e.to_string())?;
Ok(Markup::raw_unchecked(format!("<p class=\"lat-widget__name\">{count}</p>")))
}
}
fn register(&self, registry: &mut laterite_core::Registry) {
registry.add_widget(
WidgetReg::new(Arc::new(Sales)).position(Position::new().slot(slot::APPLICATION)),
);
}
| Method | Returns | Default |
|---|---|---|
code | vendor.name, unique across modules | required |
label | the heading, a Text | required |
description | a line under the label in Add widget | none |
permission | the permission an operator needs to see it | shown to every operator |
size | Size::Third, Size::Half, Size::Full: 7, 10 or 20 of the board’s columns when first placed | Half |
refresh | seconds between fetches of the body | rendered once with the page |
render | the body as Markup; an Err shows a notice inside the frame | required |
WidgetCx gives db(), base(), t(&Text), shell, user and size.
Arrange the dashboard
[backend.order]
"backend.dashboard" = ["acme.sales", "backend.welcome"]
Widgets sit in the backend.dashboard hierarchy; a widget may take
slot::HOME, slot::APPLICATION or slot::SYSTEM, and lands in
slot::APPLICATION unless its position says otherwise.
Replace a built-in widget
| Code | Shows | Permission |
|---|---|---|
backend.welcome | the operator’s name | none |
backend.manage | a card per section they may open | none |
backend.activity | the latest audit-log entries, refreshed every minute | backend.view_audit_log |
backend.status | the framework version, database and timezone | backend.manage_plugins |
A module registering a widget under a built-in’s code replaces it.
Boards
A board is a dashboard a screen hosts: widgets on a twenty-column grid, each fetched after the page opens, arranged by the people who may.
Host a board
use laterite_admin::board::{Board, BoardCx, Layout, Placement};
use laterite_admin::routes::{RouteCtx, Screen};
use laterite_admin::{AuthenticatedUser, PageHead, Shell};
struct Sales;
impl Screen for Sales {
fn mount(&self, ctx: &RouteCtx) -> Router {
let board = Arc::new(
Board::new(
"acme.sales",
Layout::rows(vec![
vec![Placement::new("orders", "acme.orders_today", 7).locked()],
vec![Placement::new("trend", "acme.revenue", 20)
.properties(json!({ "days": "30" }))],
]),
)
.edit_permission("acme.view_sales")
.share_permission("acme.manage_sales")
.offer(["acme.*"]),
);
let (page, ctx, base) = (board.clone(), ctx.clone(), ctx.base_path().to_string());
Router::new()
.route("/", get(move |Extension(shell): Extension<Shell>,
Extension(user): Extension<AuthenticatedUser>,
Query(query): Query<HashMap<String, String>>| {
let (board, ctx, base) = (page.clone(), ctx.clone(), base.clone());
async move {
let cx = BoardCx { ctx: &ctx, shell: &shell, user: &user, query: &query, width: 20 };
let body = board.body(&cx, &base).await;
shell.page_with(PageHead::new(t!("Sales")).assets(&board.assets(&ctx)), body)
}
}))
.merge(board.routes(ctx))
}
}
Board method | Sets | Default |
|---|---|---|
new(key, layout) | the key its layouts are kept under, and the widgets it starts with | required |
editing(Editing) | Off, Personal, Shared or Both | Both |
view_permission(p) | who may open it; its routes refuse anyone else | whoever reaches the screen |
edit_permission(p) | who arranges their own | whoever sees the board |
share_permission(p) | who changes the layout everyone sees | nobody |
allow(Allow) | which of moving, resizing, adding, removing and configuring edit mode offers | all |
offer(codes) | the kinds Add widget lists; acme.* is every kind under a prefix | every registered kind |
with_kind(kind) | a kind this board alone offers | none |
rows() | each row on its own line | a widget sits under the one above it in its columns |
carry(names) | query parameters the board’s requests keep, such as range | none |
Placement method | Sets |
|---|---|
new(id, kind, width) | the widget’s id on this board, its kind’s code, its columns of 20 |
properties(json) | its settings |
locked() | not moved, resized or removed |
keep() | no Remove |
fixed_settings() | no Configure |
Write a kind of widget
use laterite_admin::board::{BoardCx, Kind, KindReg};
use laterite_admin::form::FormField;
struct Revenue;
#[laterite_core::strata::async_trait]
impl Kind for Revenue {
fn code(&self) -> &str {
"acme.revenue"
}
fn label(&self) -> Text {
t!("Revenue")
}
fn group(&self) -> Text {
t!("Sales")
}
fn default_width(&self) -> u8 {
10
}
fn properties(&self) -> Vec<FormField> {
vec![FormField::of("days", t!("Days"), "select")
.options(json!({ "options": [{ "value": "7", "label": "7" }, { "value": "30", "label": "30" }] }))]
}
fn title(&self, shell: &Shell, properties: &Value) -> Option<String> {
Some(shell.t("Revenue"))
}
async fn render(&self, cx: &BoardCx<'_>, properties: &Value) -> Result<Markup, String> {
let days = properties["days"].as_str().unwrap_or("30");
acme::revenue::chart(cx.ctx.db(), days).await.map_err(|e| e.to_string())
}
}
fn register(&self, registry: &mut laterite_core::Registry) {
registry.add(KindReg::new(Arc::new(Revenue)));
}
Kind method | Returns | Default |
|---|---|---|
code | vendor.name, unique across modules | required |
label, group, description | its entry in Add widget | group Widgets, no description |
permission | the permission needed to see or add it | none |
default_width, min_width, max_width | columns of 20 | 7, 3, 20 |
resizable | whether its width changes | true |
once | at most one on a board | false |
bare | drawn with no card around it | false |
properties | its settings as form fields; with none it has no Configure | none |
properties_for(cx, current) | the fields for a widget whose settings are current, where one setting decides another’s choices | properties() |
reload_on | the settings whose change draws Configure again through properties_for | none |
check(properties) | Err with what to tell the person; nothing is saved | Ok |
title | the heading above it | none |
refresh | seconds between fetches | fetched once |
render | the content as Markup; an Err is shown in the widget’s place | required |
BoardCx gives ctx, shell, user, query (the page’s query string) and width.
Let a caller read a widget
use laterite_admin::board::ReadCx;
use laterite_core::serde_json::{json, Value};
fn reads(&self) -> bool {
true
}
async fn data(&self, cx: &ReadCx<'_>, properties: &Value) -> Result<Value, String> {
let from = cx.query.get("from").map(String::as_str);
let points = acme::revenue::by_day(cx.ctx.db(), properties["currency"].as_str(), from).await?;
Ok(json!({ "points": points }))
}
let board = Arc::new(board);
ctx.add_surface(board.surface("/acme/sales", t!("Sales")));
Kind method | Returns | Default |
|---|---|---|
reads | whether data answers | false |
data(cx, properties) | what the widget shows, as JSON | Err |
ReadCx gives ctx, user and query. Board::surface(path, label) is the
board as a surface:
| Part | Controls | Acts |
|---|---|---|
| the board | each name it carries | show |
| each widget, by its placement id | its properties, and what the board carries where it reads | read where it reads |
Charts
A chart draws series of values over a period on a screen: as lines, bars or stacked bars, with a period bar above and a legend that hides and shows series.
Draw a chart
use chrono::Utc;
use laterite_admin::axum::extract::Query;
use laterite_admin::axum::response::Response;
use laterite_admin::axum::Extension;
use laterite_admin::chart::{Chart, ChartQuery, Kind, Period, Series, CHART_ASSETS};
use laterite_admin::{html::Markup, PageHead, Shell};
use laterite_core::t;
async fn orders(
Query(query): Query<ChartQuery>,
Extension(shell): Extension<Shell>,
) -> Response {
let period = Period::from_query(&query, Utc::now().date_naive());
// (day, value) rows for period.from()..=period.to().
let web = acme::orders::by_day("web", period.from(), period.to()).await;
let shop = acme::orders::by_day("shop", period.from(), period.to()).await;
let chart = Chart::new("orders", period.clone())
.title(t!("Orders"))
.kind(Kind::StackedBar)
.series(Series::daily("web", t!("Website"), &period, web))
.series(Series::daily("shop", t!("Shop"), &period, shop));
let mut body = period.bar(&shell, &query).into_string();
body.push_str(chart.render(&shell, &query).as_str());
shell.page_with(
PageHead::new(t!("Orders")).assets(CHART_ASSETS),
Markup::raw_unchecked(body),
)
}
Period
Period::from_query(&query, today) reads these query parameters.
| Parameter | Values | Result |
|---|---|---|
range | 7d, 30d, 90d | The last 7, 30 or 90 days. 30d when absent. |
range | month, last_month | This calendar month to today; the whole of last month. |
range | 12m | The last 12 calendar months, a point a month. |
range | custom | from to to, both YYYY-MM-DD, at most 1830 days. |
by | day, week, month | The interval. day up to 370 days. |
| Method | Returns |
|---|---|
from(), to() | The first and last day. |
interval() | Interval::Day up to 92 days, Week up to 370, else Month, unless by set it. |
points() | The first day of each point. |
previous() | The period of the same length ending the day before. |
query() | The period as query parameters, for a link. |
bar(&shell, &query) | The period bar: the presets and a from and to date. |
Series
// Dated rows: summed into the period's points, a missing point is zero.
Series::daily("web", t!("Website"), &period, vec![(day, 12.0)]);
// One value a point, in order.
Series::new("web", t!("Website"), vec![12.0, 9.0, 14.0]);
Chart
| Method | Default | Effect |
|---|---|---|
Chart::new(id, period) | id names the chart on the page: letters, digits, -, _. | |
.kind(Kind) | Kind::Line | Line, Bar or StackedBar. |
.format(Format) | Format::Number | Number, or Money("EUR".into()) for EUR 1,234.50. |
.title(text) | none | The heading above the legend. |
.series(series) | Adds a series; its colour follows its place. | |
.render(&shell, &query) | The chart, showing the series show_<id> names. |
Figures
use laterite_admin::chart::{stats, Format, Stat};
let row = stats(&shell, &[
Stat::new(t!("Orders"), Format::Number.text(1284.0)).note(t!("In this period")),
Stat::new(t!("Revenue"), Format::Money("EUR".into()).text(9120.5)),
]);
Colours
A skin sets --chart-1 to --chart-6.
:root { --chart-1: #0b6e4f; --chart-2: #c8553d; }
Settings Models
A settings model is a struct an operator edits from the admin panel.
Define one
use laterite_admin::settings::SettingsModel;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SiteSettings {
#[serde(default)]
pub title: String,
#[serde(default)]
pub tagline: String,
#[serde(default)]
pub maintenance_mode: bool,
}
impl SettingsModel for SiteSettings {
const CODE: &'static str = "acme.site";
}
Derive Serialize, Deserialize and Default, and give every field
#[serde(default)]. CODE is the model’s key: namespace it to your
application and never change it.
Read and write
let settings: SiteSettings = laterite_admin::settings::load(&db).await?;
let settings = SiteSettings { title: "Acme".into(), ..Default::default() };
laterite_admin::settings::save(&db, &settings).await?;
load returns Default when nothing is saved. save upserts the whole
struct. By code, untyped:
let value = laterite_admin::settings::get(&db, SiteSettings::CODE).await?;
laterite_admin::settings::set(&db, "acme.site", &value.unwrap_or_default()).await?;
Edit it in the admin
Write the screen as a file beside the crate and register it from your
module’s register:
# admin/settings.yaml
code: acme.site
label: Site
description: Public site title, tagline, and a maintenance switch.
category: General
icon: sliders-horizontal
permission: acme.manage_site
order: 10
fields:
title: { label: Site title, rules: [required] }
tagline: {}
maintenance_mode: { type: switch }
registry.add_settings(laterite_admin::settings!("admin/settings.yaml"));
code is the model’s CODE. fields takes the entries a form descriptor
takes: see Form Descriptor. A label left out
is the field name, humanized. The file is read at compile time; a file read at
run time goes through laterite_admin::settings::from_yaml(text, name).
| Key | Default | Meaning |
|---|---|---|
code | required | The model’s CODE. |
label | required | The menu label. |
description | none | Under the label in the settings index. At most 72 characters. |
hint | none | Above the form. |
category | the band’s name | Groups items in the index, in order of first appearance. |
icon | a generic glyph | An icon. An unknown name stops the boot. |
permission | any operator | Hides the item from operators without the grant. |
order, slot | 0, application | Sort within the band; the band (laterite_core::arrange::slot). |
per_operator | false | A value kept per operator; see below. |
confirm_leave | true | Ask before leaving with changes unsaved. |
The same screen, built in Rust:
use laterite_admin::form::FormField;
use laterite_admin::settings::SettingsItem;
registry.add_settings(
SettingsItem::new("acme.site", "Site", vec![
FormField::text("title", "Site title"),
FormField::text("tagline", "Tagline"),
FormField::switch("maintenance_mode", "Maintenance mode"),
])
.description("Public site title, tagline, and a maintenance switch.")
.category("General")
.order(10)
.icon("sliders-horizontal")
.permission("acme.manage_site"),
);
One screen lists every item by category; one form edits each.
| Builder | Description |
|---|---|
new(code, label, fields) | The model’s CODE, the menu label, and its fields. |
description(text) | Under the label in the settings index. At most 72 characters. |
hint(text) | Above the form. |
category(text) | Groups items in the index, in order of first appearance. |
slot(n) | The band (laterite_core::arrange::slot); application unless set. |
order(n) | Sort within the band. |
icon(name) | An icon. An unknown name stops the boot. |
permission(code) | Hides the item from operators without the grant. |
link(path) | Places an existing screen in the settings menu, with no form. |
confirm_leave(false) | Leaving the screen with changes unsaved does not ask. |
Headings
use laterite_admin::settings::category;
SettingsItem::new("acme.webhook_log", "Webhook Log", Vec::new())
.category(category::LOGS)
.link("/acme/webhook-log");
| Constant | Heading | Holds |
|---|---|---|
category::WEBSITE | Website | Themes, Maintenance Mode |
category::USERS | Users | Administrators, Roles |
category::MAIL | Mail Configuration, Mail Templates, Mail Branding | |
category::LOGS | Logs | Audit Log, Access Log, Request Log, Mail Log |
category::SYSTEM | System | Admin Branding, Plugins, Jobs, Scheduled Tasks |
Items naming the same heading share it, whatever their band. Labels are in title case.
Fields are ordinary FormFields: text,
textarea, switch, select, date, taglist, repeater, and any registered type
through FormField::of(name, label, "vendor.type"). A type that refuses its
input refuses the save.
A type’s keys go through options; a dependency through its builder:
FormField::textarea("notice", "Notice").options(serde_json::json!({ "rows": 4, "grow": false }))
FormField::text("slug", "Slug").preset("title", PresetShape::Slug)
FormField::date("send_at", "Send date").trigger(Trigger::new("show", "is_delayed", "checked"))
Keep a value per operator
use laterite_admin::settings::{load_for, save_for, PreferencesModel, SettingsItem};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Desk {
#[serde(default)]
pub greeting: String,
#[serde(default)]
pub compact: bool,
}
impl PreferencesModel for Desk {
const CODE: &'static str = "acme.desk";
}
registry.add_settings(
SettingsItem::new("acme.desk", "My desk", vec![
FormField::text("greeting", "Greeting"),
FormField::switch("compact", "Compact rows"),
])
.description("How the desk greets you.")
.per_operator(),
);
let desk: Desk = load_for(&db, user.user.id).await?;
save_for(&db, user.user.id, &Desk { compact: true, ..desk }).await?;
| Item | Description |
|---|---|
PreferencesModel | The same shape as SettingsModel; CODE is the key, one value per operator. |
.per_operator() | Keeps the item once per operator and lists it on their Preferences page, under More, at /preferences/<code>. The permission still applies; the category is not used. |
load_for, save_for | One operator’s model, or the default when they have none; a write for one operator. |
get_for, set_for | The same, as raw JSON. |
| Audit | A deployment setting’s save is audited; an operator’s own preference is not. |
Link a screen into the settings menu
registry.add_settings(
SettingsItem::new("acme.pages", "Pages", Vec::new())
.description("Manage site pages.")
.category("Content")
.icon("folder")
.link("/pages"),
);
The path is under the admin mount. Any request at or under it renders the settings sidebar with the item active. The built-in Users and Roles register this way.
Change a model later
| Change | Migration |
|---|---|
| Add a field | None. A missing key deserializes to the field’s default. |
| Remove a field | None. A stale key is ignored. |
| Rename a field | Read the old key, write the new one. Never reuse a CODE for an incompatible model. |
Parameters
A parameter is a JSON value a module writes for itself, under a
namespace::group.item key.
Read and write one
use laterite_core::parameters;
parameters::set(ctx.db(), "acme.blog::sync.cursor", &cursor).await?;
let cursor: Option<Cursor> = parameters::get(ctx.db(), "acme.blog::sync.cursor").await?;
let removed = parameters::reset(ctx.db(), "acme.blog::sync.cursor").await?;
| Function | Description |
|---|---|
get::<T>(db, key) | Ok(None) when unset. |
get_value(db, key) | The raw serde_json::Value. |
set(db, key, &value) | Replaces any value held. |
reset(db, key) | Removes it; true when one was set. |
| Key part | Holds |
|---|---|
namespace | The owning module’s id: acme.blog. |
group | A family of items: sync. |
item | The item; may contain dots. |
A malformed key is CoreError::Validation.
Go through the cache
let parameters = ctx.parameters();
parameters.set("acme.blog::sync.cursor", &cursor).await?;
let page: u32 = parameters.get_or("acme.blog::sync.page", 1).await?;
parameters.forget("acme.blog::sync.cursor");
| Method | Description |
|---|---|
get, get_or, set, reset | As the functions, through the cache. |
forget(key) | The next read goes to the database. |
clear() | Drops every entry. |
with_ttl(duration) | On Parameters::new(db); the default is five minutes. |
Read a key the framework writes
| Key | Value |
|---|---|
laterite.backend::setup.completed_at | RFC 3339, written when the first administrator is created. The constant is laterite_admin::SETUP_COMPLETED_AT. |
Add it to a module list
use laterite_core::parameters::ParametersModule;
laterite_admin::builtin_modules() includes it; an application composing its
own list adds ParametersModule.
Logs
The admin keeps three read-only logs under Settings → System: the audit log of administrative changes, the access log of sign-ins, and the request log of URLs it could not serve. Each is gated by its own permission and exportable.
Read the audit log
Every administrative change is recorded in an append-only log; handlers do not
opt in. Gated by backend.view_audit_log; superusers hold it.
| Field | Value |
|---|---|
| When | The time of the change. |
| Operator | The username, kept on the entry after the account is removed. A system change records the process name. |
| Action | A dot-keyed name: backend.role.update, backend.plugin.disable. |
| Target | A type, id and name, when the action has one. |
| Change | Recorded |
|---|---|
| A role created or edited | Yes |
| A user’s permissions changed | Yes |
| A password changed | Yes, as backend.user.password_change, never the password |
An operator created from setup or lat admin create | Yes, as backend.user.create, credited to the process |
| A plugin enabled or disabled | Yes |
| A settings model saved | Yes, without the contents |
| A record created or edited through a resource form | Yes |
| An operator’s own preferences | No |
Read the access log
Every sign-in, failure, lockout, sign-out and self-service password change,
with the address and client it came from. Gated by backend.view_access_log.
| Column | Holds |
|---|---|
| When | The time of the event. |
| Username | The username attempted, searchable. |
| Event | One of the events below; a filter narrows to one. |
| Address | The IP address, searchable. |
| Client | The user agent; hidden until turned on in the list setup. |
| Event | Recorded when |
|---|---|
login_success | A sign-in succeeded. |
login_failure | A password was wrong, or the username unknown. |
locked_out | An attempt was refused by the lockout. |
logout | An operator signed out. |
password_changed | An operator changed their own password. |
Rows older than access_log_retention_days (see Authentication) are purged hourly.
Read the request log
Every URL the admin could not serve is counted, once per method, path and
status, with the first and last time it was seen. Gated by
backend.view_request_log.
# descriptors/request-log.yaml, built in
entity: backend_request_log
path: /request-log
permission: backend.view_request_log
| Column | Holds |
|---|---|
| Last seen, First seen | When the URL was last and first requested. |
| Method, Path | The request; the path is kept to 512 characters, without its query string. |
| Status | 404. |
| Hits | How many times. |
Rows are selected and deleted like any list’s.
Write audit entries from your own resources
A Resource with a form is audited as backend.<entity>.create and
backend.<entity>.update, attributed to the signed-in operator, through a
model listener.
A screen of your own records an entry with the builder:
use laterite_auth::AuditEntry;
use laterite_core::Actor;
let actor = Actor::user(operator.id, &operator.username);
auth.record_audit(
AuditEntry::new(&actor, "acme.posts.publish").target("post", &post_id, Some(&post.title)),
)
.await?;
| Builder | Description |
|---|---|
AuditEntry::new(actor, action) | Who, and a dot-keyed action under your module’s id. |
.target(type, id, name) | What the action touched; name may be None. |
The audit write runs after the change commits. A failed audit write is logged; the operator’s action stands.
Developer Section
With app.debug on, a superuser sees a Developer section in the admin’s navigation: what the application registered, from the running process.
[app]
debug = true
| Screen | Shows |
|---|---|
| Routes | Every URL the application answers, with method, kind, owner and permission: the list lat routes prints. |
| Field types | Every registered field type, rendered once with its defaults. |
| Mail previews | Every mail template and layout, each with its preview. |
| Registries | What every module contributed, by registry: resources, screens, settings, permissions, field and column types, widgets, public routes. |
The section is absent when app.debug is off, and a 403 to an operator who is not a superuser. See Application and Server for app.debug.
Form Descriptor
One YAML file describes one resource: the table, where it mounts, who may reach
it, and its list and form. This page covers the resource keys and the form
half; the list half is on List Descriptor.
# descriptors/posts.yaml
entity: posts
path: /posts
title: Posts
permission: acme.blog.manage_posts
list:
creatable: true
deletable: true
order_by: created_at
order_dir: desc
columns:
title: { searchable: true }
status: { type: status_pill, width: 10% }
created_at: { type: datetime, align: right }
form:
title: Post
fields:
title: { span: 2/3, rules: [required, { max_length: 120 }] }
status: { span: 1/3, type: select, options: [{ value: draft, label: Draft }] }
body: { type: textarea, rows: 8 }
Register it
registry.add_resource(laterite_admin::resource!("descriptors/posts.yaml"));
The path is relative to your Cargo.toml. The file is read at compile time: a
missing or malformed one fails the build.
| Key | Description |
|---|---|
entity | The table both screens read and write. Required. |
path | Where the resource mounts, under your module’s namespace. Required. |
title | The navigation label, and the default title of both screens. Required. |
permission | The permission gating it. Required once a form is present. |
id_field | The primary key column. Default id. |
list | The list screen. Required. |
form | The create and edit screen. Optional. |
import | true, or { permission: ... }, to let records be imported into the resource. Needs form. See Bulk Import. Optional. |
relations | Related records, keyed by name, each a section on the edit page. See Related Records. Needs form. Optional. |
source | Keeps the records as files in a folder of the project. See Records in Files. Needs form. Optional. |
entity, path and id_field reach both screens.
Name a field
Fields are a map. The key is the name, and they render in the order written:
fields:
title: {}
published_at: { type: date }
A missing label is made from the key: published_at becomes “Published at”.
It is still translatable, and lat i18n extract finds it.
Set a field’s keys
An entry carries its own keys and its type’s, side by side:
fields:
body: { type: textarea, rows: 8, placeholder: Write here, span: 1/2 }
price: { input: number, min: 0, step: 0.01, help: In the shop's currency }
status: { type: select, options: [{ value: draft, label: Draft }], hidden: true }
| Key | Default | Description |
|---|---|---|
label | from the key | The label shown. |
type | text | The field type. Every type and its keys: Form Fields. |
rules | none | Validation rules run on submit. See Validation. |
help | none | A line beneath the control. |
span, break | full, false | The field’s place on the row. See below. |
enter | the form’s | submit, off, next. |
preset, trigger | none | Follows or watches another field. See Field Dependencies. |
format | none | The shapes accepted, the one stored, and how a link column shows it. See Field Formats. |
hidden | false | Submitted but never shown: a plain hidden input carrying its value. |
transient | false | Shown and submitted with no column behind it: not loaded, not written by the built-in writer; the form’s persist handler reads it (a password field). |
translatable | false | Marks the value as translatable content, for a translation plugin to manage. |
context | every page | The pages the field is on: create, update, preview, one or a list. See below. |
default | none | What a new record’s form opens with: text, a number, true or false, or a list for a field holding several. |
default_from | none | Another field whose default this one opens with. |
help_above | none | Text above the control, under the label. |
css_class | none | Classes added to the field’s wrapper. |
container_attributes | none | Attributes added to the field’s wrapper, as a map. An event handler, class, style, id and data-lat-* are refused. |
read_only | false | Shown with its value, not editable. A save keeps what is stored; a new record takes the field’s default. |
disabled | false | Shown, not editable, and left out of every save. |
permission | none | A permission the user must hold to see the field or write it. An editable list cell of the field follows the same rule. |
depends_on | none | A field, or a list of fields: when one changes, this field is drawn again. See Field Dependencies. |
A key the type does not read is refused, naming the entry and the keys it accepts.
Put fields on tabs
form:
fields:
title: {}
tabs:
default_tab: Details
active_tab: Pricing
icons: { Details: file-text, Pricing: tag }
fields:
body: { type: textarea }
price: { tab: Pricing, input: number }
stock: { tab: Pricing, input: number }
secondary_tabs:
fields:
notes: { tab: Notes, type: textarea }
| Part | Holds |
|---|---|
fields | The fields above the tabs. One naming a tab joins the tabs. |
tabs.fields | The fields on the tabs, each on the tab it names. |
secondary_tabs.fields | A second set of tabs, under the first. |
Key of tabs and secondary_tabs | Default | Description |
|---|---|---|
default_tab | Misc | The tab for a field in the set that names none. |
active_tab | the first | The tab open on load: its label, or its place from 1. |
icons | none | An icon for a tab, by the tab’s label. |
linkable | true | A tab opens by the address’s fragment, and writes it. |
stretch | false | The panes fill the height left on the page. |
css_class | none | A class on the set. |
pane_css_class | none | A class on every pane, or a map of tab label to class. |
identifiers | from the label | An HTML id for a tab, by its label. |
Tabs show in the order their fields first name them. A refused save opens the first tab holding a refused field.
lat.get(document.querySelector('[data-lat-widget="formtabs"]')).open('tab-pricing');
lat.on('formtabs:opened', function (detail) { console.log(detail.tab); });
FormField::text("price", t!("Price")).tab(t!("Pricing"));
Keep a field to some pages
fields:
code: {}
token: { context: create }
notes: { type: textarea, context: [update, preview] }
status@create: { type: select, options: [{ value: draft, label: Draft }] }
status@update: { type: select, options: [{ value: draft, label: Draft }, { value: live, label: Live }] }
| Form | Meaning |
|---|---|
context: update | On that page alone. |
context: [create, update] | On each page listed. |
name@update | The same, written on the key. One column may have an entry a page. |
| Page | Route |
|---|---|
create | {path}/new |
update | {path}/{id}/edit |
preview | {path}/{id}/preview |
A field off a page is not shown, checked or saved there. An import and an ability write through every field.
FormField::text("token", t!("Token")).context([FormContext::Create]);
Set the form’s keys
form:
enter: off
confirm_leave: false
focus: off
timestamps: true
footprints: true
slugs: { slug: title }
encrypt: [api_key]
actions:
- { label: Reset to default, action: "acme/templates/{id}/reset", confirm: Reset this template? }
- { label: Download PDF, action: "acme/templates/{id}/pdf", method: get }
fields:
title: { rules: [{ max_length: 80 }], counter: true }
body: { type: textarea, rows: 8, grow: false }
token: { type: password, reveal: false }
| Key | On | Values | Default |
|---|---|---|---|
title | The form | text | The resource’s title |
enter | The form | submit, off | submit: Enter submits; Cmd/Ctrl+Enter submits from a textarea as well |
confirm_leave | The form | true, false | true: leaving with changes unsaved asks first |
focus | The form | auto, off | auto: a new record opens with the cursor in its first field, a refused save in the first field it refused |
timestamps | The form | true, false | false; true stamps created_at and updated_at on write |
footprints | The form | true, false | false; true stamps created_user_id and updated_user_id. See Model listeners |
slugs | The form | a map of slug column to a source column or a list | None. See Model listeners |
encrypt | The form | a list of columns | None. See Model listeners |
related | The form | a map of one-to-one records | None. See Related Records |
related | A field | a name under the form’s related | None: the field is stored on that record |
persist | The form | a persister name | The built-in insert and update. See Persisters |
actions | The form | a list of label, action (a path under the admin root, {id} for the record), method (post or get), confirm, permission (hides the button without the grant) | None. Shown beside Save on an existing record; post submits the form to action, get links to it |
after_save | The form | create, update, close (paths under the admin root, {id} for the record), created, updated (text) | Save returns to the list and says “Saved.”. create and update send Save elsewhere, and that page then offers “Save and close”, which goes to close or the list |
panels | The form | a list of src, title, permission, as a preview’s panels | None. Drawn under an existing record’s form, each fetched from src once the page is open |
linked_record | The form | morph (the name n of the columns n_type and n_id), label, empty | None. Links the owning record above an edit form, named by its resource’s title and its list’s first column; empty (“Not linked”) shows when the columns are empty |
enter | A field | submit, off, next | The form’s |
A max_length rule also sets the control’s maxlength.
Preview a record
# descriptors/orders.yaml
preview:
title: Order
assets: [chart.css]
panels:
- { title: Payments, src: "acme/orders/{id}/payments", permission: acme.payments }
list:
row_click: preview
preview: true takes every default.
preview:
fields:
code: { label: Reference }
total: { input: number }
relations: false
| Key | Default | Description |
|---|---|---|
title | the form’s | The page’s title. |
assets | none | Asset keys the panels need on the page. |
panels | none | Parts drawn under the values, in order. |
fields | the form’s on preview | The preview’s own fields, written as the form’s are. |
relations | true | The record’s related lists show under the values, to read. |
| Panel key | Description |
|---|---|
src | A path under the admin root answering an HTML fragment, {id} for the record’s id. Fetched once the page is open. |
title | The heading over the panel. |
permission | A user without it does not get the panel. |
| Route | Shows |
|---|---|
{path}/{id}/preview | The form’s fields with their values, none editable, an Edit button, then the panels. |
A previewed resource’s list shows a Preview link on each row, before Edit.
Lay out the fields
Fields lay out on a twelve-column row and wrap as it fills.
fields:
title: { span: 2/3 }
status: { span: 1/3 }
body: { break: true }
| Key | Description |
|---|---|
span | The share of the row: full (default), 1/2, 1/3, 2/3, 1/4, 3/4, or 1 to 12 columns. left, right, auto and half are halves; third and quarter as named. |
break | true starts a new row. |
Under 1100px a quarter becomes a half; under 768px every field takes the row.
Catch a bad key
A key the framework does not know is refused with its line:
error: line 11 column 19: unknown field `searchabel`, expected one of
label, type, sortable, invisible, width, align, permission, searchable
Write only the keys you set; everything else takes its default.
lat doctor parses every descriptors/**/*.yaml in the application and its
plugins and names a typo without a build.
Read a descriptor at run time
resource! embeds a file. For YAML you loaded yourself, call the function
behind it:
let resource = laterite_admin::descriptor::from_yaml(&yaml, "posts.yaml")?;
Field Dependencies
A field follows another as it is typed, or changes when another field’s state meets a condition.
fields:
title: {}
slug: { preset: title }
path: { preset: { field: title, type: url } }
is_delayed: { type: switch, label: Send later }
send_at:
type: date
trigger: { action: show, field: is_delayed, condition: checked }
format: { type: select, options: [{ value: csv }, { value: xml }] }
delimiter:
trigger: { action: show|empty, field: format, condition: "value[csv]" }
topics: { type: checklist, options: [{ value: news }, { value: sport }] }
region:
trigger: { action: enable, field: "topics[]", condition: "value[sport]" }
Follow another field
| Key | Value |
|---|---|
preset | The field followed, or { field, type }. Follows it as it is typed, until this field is edited; emptying this field hands it back. |
preset.type | slug (default): hello-world. url: /hello-world. file: spaces to hyphens. exact: as typed. |
React to another field
| Key | Value |
|---|---|
trigger.action | show, hide, enable, disable, empty, fill[value], several joined by |. A hidden field is left out of the submission. |
trigger.field | The field watched. name[] watches every ticked value of a checklist. |
trigger.condition | checked, unchecked, value[x], value[x][y] (either), value[] (empty), value[*] (anything), value[csv*] (a prefix). |
A field that follows or watches one the form does not have stops the boot, naming it. An action or condition the page does not know is refused when the file is read.
Options from a source
fields:
country: { type: select, options: acme.countries }
state: { type: select, options: acme.states, depends_on: country }
timezone: { type: select, options: laterite.timezones }
use laterite_admin::options::{OptionCx, OptionEntry, OptionError, OptionSource, OptionSourceReg};
struct States;
#[async_trait]
impl OptionSource for States {
async fn options(&self, db: &Db, cx: &OptionCx<'_>) -> Result<Vec<OptionEntry>, OptionError> {
let country = cx.values.get("country").map(String::as_str).unwrap_or("");
Ok(states_of(db, country)
.await?
.into_iter()
.map(|s| OptionEntry::new(s.code, s.name))
.collect())
}
}
registry.add_option_source(OptionSourceReg::new("acme.states", Arc::new(States)));
registry.add_option_source(OptionSourceReg::fixed(
"acme.sizes",
vec![OptionEntry::new("s", "Small"), OptionEntry::new("l", "Large").note("From 40 cm")],
));
| Key | Value |
|---|---|
options | On a select, radio or checklist: the name of a registered source, in place of a list. |
depends_on | A field, or a list of fields. When one changes, this field is drawn again and its source is asked with the form’s current values. |
OptionCx | Holds |
|---|---|
field | The field’s name. |
value | The field’s current value. |
values | Every value the form holds, by field name. For a list filter: every filter value, by filter name. |
id | The record being edited, on an edit page. |
i18n | The request’s translator. |
OptionEntry | Effect |
|---|---|
::new(value, label) | A choice storing value, shown as label. |
.note(text) | A second line under the label (radio, checklist). |
.disabled() | Shown and not selectable (select, radio). |
.group(heading) | Sits under heading (select, checklist). |
| Built-in source | Offers |
|---|---|
laterite.timezones | Every timezone name. |
laterite.locales | The languages the admin is translated into. |
A source name nobody registered, a field depending on one the form does not
have, and a field depending on itself stop the boot. A row of a repeater
lists its options in place.
Field Formats
A format says what a value looks like. The form accepts the shapes people
type and stores one; a link column on the same field shows it short and
linked.
form:
fields:
instagram_url:
label: Instagram
format: { base: "https://www.instagram.com/", prefix: "@", pattern: "[A-Za-z0-9._]{1,30}", lowercase: true }
list:
columns:
instagram_url: { type: link, new_tab: true }
FormField::text("instagram_url", t!("Instagram")).format(
FieldFormat::new("https://www.instagram.com/").prefix("@").pattern("[A-Za-z0-9._]{1,30}").lowercase(),
)
| Key | Default | Description |
|---|---|---|
base | required | The address every value sits under, ending in /. A path is allowed: https://www.linkedin.com/in/. |
prefix | none | Shown before the name, and accepted before it when typed. |
pattern | any | A regular expression the whole name must match. |
lowercase | false | Stores the name lowercased. |
name_only | false | Stores the name alone, acme, in place of the address. |
What the form accepts
| Typed | Stored |
|---|---|
https://www.instagram.com/acme/?igsh=1 | https://www.instagram.com/acme |
instagram.com/acme | https://www.instagram.com/acme |
@acme | https://www.instagram.com/acme |
acme | https://www.instagram.com/acme |
| Empty | Empty; add required to refuse it |
Another site, a path or a name pattern refuses | Refused on the field |
What the list shows
| Stored | Shown |
|---|---|
https://www.instagram.com/acme | @acme, linked |
| A value saved before the format | As stored |
A link column reads its field’s format; format on the column itself
overrides it, for a list with no form.
list:
columns:
profile: { type: link, format: { base: "https://www.tiktok.com/", prefix: "@" } }
Related Records
A resource lists another entity’s records that belong to each of its own, as a section on the edit page. A has-many section has New, Edit and Delete; a many-to-many section has Attach, Edit and Remove.
Declare a has-many relation
# descriptors/products.yaml
relations:
variants:
label: Variant
entity: product_variants
foreign_key: product_id
list:
columns:
sku: {}
price: { type: money }
form:
fields:
sku: { rules: [required] }
price: { type: money }
Resource::new("/products", "Products", list)
.form(form)
.permission("acme.manage_products")
.relation(RelationConfig::has_many("variants", "Variant", "product_variants", "product_id", variants_list, variants_form))
Declare a many-to-many relation
# descriptors/products.yaml
relations:
tags:
label: Tag
entity: tags
pivot:
table: product_tags
parent_key: product_id
related_key: tag_id
source: acme.tags
list:
columns:
name: {}
form:
fields:
note: {}
Resource::new("/products", "Products", list)
.form(form)
.permission("acme.manage_products")
.relation(
RelationConfig::belongs_to_many(
"tags",
"Tag",
"tags",
PivotConfig::new("product_tags", "product_id", "tag_id", "acme.tags"),
tags_list,
)
.form(note_form),
)
// The picker source Attach searches, registered with the admin.
Contributions {
picker_sources: vec![PickerSourceReg::new(
"acme.tags",
Arc::new(TableSource::new("tags", "id", "name")),
)],
..Default::default()
}
Declare a polymorphic relation
# descriptors/notes.yaml, and the same in descriptors/tasks.yaml
relations:
comments:
label: Comment
entity: comments
morph: commentable
list:
columns:
body: {}
form:
fields:
body: { rules: [required] }
tags:
label: Tag
entity: tags
pivot:
table: taggables
parent_key: taggable_id
parent_type: taggable_type
related_key: tag_id
source: acme.tags
list:
columns:
name: {}
RelationConfig::has_many("comments", t!("Comment"), "comments", "", list, form).morph("commentable");
PivotConfig::new("taggables", "taggable_id", "tag_id", "acme.tags").parent_type("taggable_type");
| Column | Holds |
|---|---|
commentable_id | The parent’s id |
commentable_type | The parent’s entity, such as notes |
taggable_type | On the pivot: the parent’s entity |
The type columns are written from the URL and kept hidden in the form. A section lists only rows whose type is its parent’s entity.
Edit a one-to-one record in the form
# descriptors/authors.yaml
form:
related:
profile: { entity: profiles, foreign_key: author_id }
address: { entity: addresses, belongs_to: address_id }
fields:
name: { rules: [required] }
bio: { related: profile }
city: { related: address }
form.related.insert("profile".into(), RelatedRecord::has_one("profiles", "author_id"));
form.related.insert("address".into(), RelatedRecord::belongs_to("addresses", "address_id"));
related key | Holds |
|---|---|
entity | The related table |
foreign_key | Has-one: the related table’s column holding this record’s id |
belongs_to | Belongs-to: this table’s column holding the related record’s id |
id_field | The related table’s id column; default id |
timestamps | true: the related row’s created_at and updated_at are stamped as it is written |
optional | Belongs-to, true: with every field of it empty no record is made, and one already there is let go (this record’s column is cleared, the related row stays) |
| Step of a save | Writes |
|---|---|
| 1 | Each belongs-to record, inserted or updated; its id goes into this record’s column |
| 2 | This record |
| 3 | Each has-one record, inserted or updated with this record’s id |
| 4 | The media links of this record’s media fields |
All four run in one transaction: a failure in any of them saves none. A field
with related cannot carry unique.
Delete related rows with their parent
# descriptors/notes.yaml
soft_delete: true
relations:
comments:
title: Comments
entity: comments
morph: commentable
soft_delete: true
delete: true
section: false
RelationConfig::has_many("comments", t!("Comment"), "comments", "note_id", list, form)
.delete()
.section(false)
| Parent | soft_delete | delete |
|---|---|---|
| Moved to the trash | Rows go to the trash with it | |
| Restored | Rows that went with it come back | |
| Deleted, or deleted permanently from the trash | Rows are deleted in the same transaction |
A deleted row’s own delete relations, declared on a resource over its
entity, go with it:
# descriptors/comments.yaml
entity: comments
relations:
reactions:
title: Reactions
entity: reactions
foreign_key: comment_id
delete: true
section: false
Delete asks first and names each relation by its title:
“These are deleted with them: Comments, Reactions.” The rows’ own listeners do
not run.
Set the keys
| Key | Default | Does |
|---|---|---|
label | required | One related record, singular: the New or Attach button, the child form’s title. |
title | the name, humanized | The section heading. |
entity | required | The related table. |
foreign_key | one of three | Has-many: the column on the related table holding the parent’s id. Written by the framework from the URL; a field of that name in form is kept hidden. |
morph | one of three | Polymorphic has-many: name for the name_id and name_type columns. |
soft_delete | false | Has-many: rows go to the trash with the parent and come back with it. See Soft Delete. |
delete | false | Has-many: rows are deleted with the parent. See Delete related rows with their parent. |
section | true | false gives the relation no section and no pages; soft_delete and delete still apply, and list and form are not needed. |
pivot | one of three | Many-to-many: the table joining the two, keys below. |
list | required | The section’s list: the same keys as a resource’s list. Its columns are the related table’s. |
form | required for has-many | Has-many: the related record’s form. Many-to-many: the fields kept on the pivot row, asked for on Attach; empty gives the section no Edit. |
permission | the parent’s | A permission the user must also hold. |
| Pivot key | Default | Does |
|---|---|---|
table | required | The pivot table. |
parent_key | required | The column holding the parent’s id. Written by the framework from the URL. |
related_key | required | The column holding the related record’s id. Chosen in the picker on Attach, fixed afterwards. |
source | required | The registered picker source Attach searches. |
id_field | id | The pivot row’s id column. |
parent_type | none | Polymorphic: the pivot column holding the parent’s entity. |
Reach the section
| Path | Does |
|---|---|
/products/7/edit | The parent’s form, then a section per relation. |
/products/7/variants | The section’s list on its own, sorted and paged. |
/products/7/variants/new | Has-many: a new related record. Many-to-many: Attach, a record from the picker with the pivot fields. Saves return to the parent. |
/products/7/variants/3/edit | Has-many: the related record 3. Many-to-many: pivot row 3’s fields. Only under its own parent. |
/products/7/variants/delete | Has-many: deletes the selected records through the related entity’s listeners and persister. Many-to-many: deletes the selected pivot rows the same way; the records stay. |
/products/7/variants/reorder | Has-many with reorder on its list: moves one record within the parent’s section. See Trees and Reordering. |
A relation needs a form on the parent. A relation’s name is a path segment and
cannot be new, edit, delete, import, export or columns. Attaching
a record already attached, or one the related table does not hold, is refused
with a message.
Validation
A form field carries rules. A failed submission re-renders the form with a message under each field and writes nothing.
Declare rules
use laterite_admin::form::FormField;
let fields = vec![
FormField::text("email", "Email").required().email().unique(),
FormField::text("name", "Name").required().max_length(120),
];
fields:
email: { rules: [required, email, unique] }
name: { rules: [required, { max_length: 120 }] }
| Builder | Rule |
|---|---|
.required() | Non-empty in every mode. |
.required_on(Mode::Create) | Non-empty on create, or on update, only. |
.min_length(n) / .max_length(n) | Length bounds. min is skipped when empty. |
.email() | A valid email address. |
.unique() | Not already used in the column. Ignores the edited row on update. |
The generic create and edit handlers validate before writing.
Call the engine
use laterite_core::validation::{validate, FieldRules, Mode, Rule};
let rules = vec![FieldRules::new("email", "Email", vec![Rule::Required, Rule::Email])];
let bag = validate(&db, "users", "id", &rules, &data, Mode::Create, None).await?;
if bag.is_empty() {
// persist
}
validate_fields runs the rules without the database; validate adds the
unique probe. The result is an ErrorBag; empty means valid.
Register a rule
use laterite_core::validation::{RuleCx, ValidationRule, ValidationRuleReg};
use laterite_core::Text;
struct DiffersFrom;
#[laterite_core::strata::async_trait]
impl ValidationRule for DiffersFrom {
async fn check(&self, cx: &RuleCx<'_>, value: &str) -> Result<(), Text> {
let other = cx.args.first().and_then(|name| cx.data.get(name));
if other.is_some_and(|o| o.trim() == value) {
return Err(Text::new("{label} must differ.").arg("label", Text::dynamic(cx.label)));
}
Ok(())
}
}
// In a module's `register`:
registry.add(ValidationRuleReg::new("acme.differs_from", Arc::new(DiffersFrom)));
fields:
code: { rules: [required, acme.uppercase, { acme.differs_from: name }] }
RuleCx field | Holds |
|---|---|
field, label | The field being checked and its label |
args | The descriptor’s arguments as text: { acme.between: [1, 10] } gives ["1", "10"] |
data | Every submitted value, by field name |
mode | Mode::Create or Mode::Update |
db, table, edited_id | The database, the form’s table, the record being updated |
A rule runs after the built-in rules pass for that field, and skips an empty
value unless implicit() returns true. A registered name is dotted
(vendor.rule). A field naming a rule no module registered fails boot.
Read what a submission answers
| Outcome | Response |
|---|---|
| Refused | 422, the form re-rendered with its values. An htmx submit swaps the form; a plain one gets the whole page. |
| Saved | A flash, then the list: HX-Redirect for htmx, 303 otherwise. |
| API | 422 with { "field": ["message", ...] }. |
Writing a Field Type
A field type renders one kind of control on any form or settings page that names it, and turns what it submits into the value that reaches the database.
Implement the type
impl FieldType for SwitchField {
fn view_key(&self) -> &'static str {
"switch"
}
fn view_model(&self, cx: &FieldCx<'_>) -> FieldVm {
scalar_vm("switch", cx)
}
fn render_default(&self, vm: &FieldVm) -> Markup {
Markup::from_template(&SwitchTmpl { vm }).unwrap_or_default()
}
fn to_attr(
&self,
field: &SubmittedField<'_>,
_opts: &ResolvedOptions,
_mode: Mode,
) -> Result<Option<AttrValue>, String> {
Ok(Some(AttrValue::Bool(stored_is_on(field.value()))))
}
}
| Method | Role |
|---|---|
view_key | The name a descriptor uses. A dotted vendor.name; a taken key aborts the boot. |
view_model | The submitted or saved value as a view-model. |
render_default | The markup. |
to_attr | The submitted string as the typed value that reaches the database. Err refuses the save. |
option_keys | The keys the type reads from a field’s entry. Any other key is refused by name. |
submitted | For a type of several controls: what it submitted, gathered into one value. The rules read it, and a refused save is rebuilt from it. |
resolve_options | Those keys, typed once. |
Built in: text, textarea, select, radio, checklist, taglist, switch, date,
password, reference, repeater.
Register it
registry.add_field_type(FieldTypeReg::new(Arc::new(MoneyField)));
FormField::of("price", "Price", "acme.money")
One registration covers forms and settings. A descriptor naming an unregistered type aborts the boot.
Declare its keys
price: { type: acme.money, currency: EUR, precision: 2, span: 1/3 }
fn option_keys(&self, _raw: &serde_json::Value) -> Option<Vec<String>> {
Some(vec!["currency".into(), "precision".into()])
}
A type’s keys are written on the field, beside the field’s own.
Meet the contract
| Rule | How |
|---|---|
| Works with no configuration | Every key has a default chosen for the common case: type: acme.money alone renders a usable control. |
| Each default can be turned off | One key per behaviour, named for what it does, read from the field’s entry. |
| Its keys are declared | option_keys lists them; a typo is refused by name. |
| Enter stays inside it | A root marked data-lat-enter-scope when the control holds an input of its own. See JavaScript API. |
| It says what it did | lat.emit(root, 'acme.money:changed', detail); a before- event is cancelable. |
| It can be driven | The island’s initialiser returns its controller; lat.get(el) finds it. |
| It is listed | One row per behaviour in your plugin’s docs: the default, and the key that changes it. See Behaviours. |
| Works before scripts load | The markup submits as a plain form; a script island improves it. |
Editor Commands and Snippets
A module adds entries to the Insert menu of the rich and markdown editors: a command that inserts fixed content, or a snippet with properties the user fills. The editors show the Insert button once at least one command or snippet exists.
Add a command
use laterite_admin::editor::{EditorCommand, Insert, Surface};
use laterite_admin::AdminRegistry;
fn register(&self, registry: &mut laterite_core::Registry) {
registry.add_editor_command(EditorCommand::new(
Surface::Rich,
"acme.callout",
t!("Callout"),
Insert::Html(r#"<blockquote><p>Note</p></blockquote>"#.into()),
));
registry.add_editor_command(EditorCommand::new(
Surface::Markdown,
"acme.callout",
t!("Callout"),
Insert::Text("> **Note**\n> ".into()),
));
}
| Field | Values |
|---|---|
Surface | Rich (the richeditor field, inserts HTML), Markdown (the markdown field, inserts text) |
key | stable within the surface; a later registration with the same key replaces the earlier |
label | a Text, localized for the user |
Insert | Html(..) for Rich, Text(..) for Markdown |
Offer snippets
use laterite_admin::editor::{Snippet, SnippetProperty, SnippetPropertyKind, SnippetSource};
struct Embeds;
#[laterite_core::strata::async_trait]
impl SnippetSource for Embeds {
async fn list(&self, _db: &laterite_core::Db) -> Vec<Snippet> {
vec![Snippet {
code: "acme.map".into(),
name: "Map".into(),
description: Some("A map centred on an address".into()),
properties: vec![SnippetProperty {
code: "address".into(),
title: "Address".into(),
kind: SnippetPropertyKind::String,
default: None,
options: Vec::new(),
}],
}]
}
}
registry.add_snippet_source(std::sync::Arc::new(Embeds));
| Field | Values |
|---|---|
SnippetPropertyKind | String, Dropdown (with options as (value, label) pairs), Checkbox |
list(db) | asked each time an editor opens its Insert menu; the list may change while the application runs |
An inserted snippet is
<figure data-snippet="<code>" data-properties="{...}"></figure>. A theme
declares snippets on its partials and renders them with the content filter; a
component is offered with ComponentReg::snippet and runs after the page
renders; see Snippets. A module that lists snippets
from a source renders them on its own pages the same way.
Read the menu
GET /admin/editor/menu?surface=richeditor
{ "commands": [{ "key": "acme.callout", "label": "Callout", "html": "..." }],
"snippets": [{ "code": "acme.map", "name": "Map", "properties": [...] }] }
List Descriptor
The list half of a resource file: its columns, search, ordering, paging and
the capabilities it offers. The resource keys around it are on
Form Descriptor.
# descriptors/posts.yaml
entity: posts
path: /posts
title: Posts
permission: acme.blog.manage_posts
list:
creatable: true
deletable: true
exportable: true
order_by: created_at
order_dir: desc
per_page: 25
per_page_options: [25, 50, 100]
no_records_message: No posts yet.
search: { prompt: Search posts }
columns:
title: { searchable: true }
status: { type: status_pill, width: 10%, labels: [{ value: draft, label: Draft }] }
created_at: { type: datetime, align: right }
filters:
status: { type: select, options: [{ value: draft, label: Draft }] }
toolbar:
- { label: Archive, href: /posts/archive, icon: archive, primary: false }
Set the list’s keys
| Key | Default | Description |
|---|---|---|
columns | The columns, keyed by field name, in order. Required. | |
related | none | One-to-one records a column can be read from, by name. |
title | the resource’s | The screen title. |
order_by, order_dir | id, desc | The first sort; asc or desc. |
per_page | 25 | Rows a page. |
per_page_options | none | Page sizes offered in the list setup; empty offers no choice. |
creatable | false | Offers New. |
deletable | false | Rows can be selected and deleted, and a record’s edit page offers Delete. |
protected | none | A boolean column; a row it marks has no checkbox and no Delete. |
exportable | false | Offers the export menu. See Export. |
search | on | The search box; keys below. |
filters | none | Filters above the table, keyed by field name. See Filters. |
no_records_message | “No records yet.” | Shown when the list has no records at all. |
row_click | open | Where a click on a row goes: open (the record’s edit page), preview (its preview), none, or an address pattern. See below. |
remember | true | The sort, search, filters and page a user last used come back when they return. |
reorder | off | true orders rows by sort_order; { column: position } names the column. See Trees and Reordering. |
tree | off | true nests rows on parent_id; { parent_key, source } names the column and a picker source for Move to. See Trees and Reordering. |
toolbar | none | Extra buttons beside New; keys below. |
import is a resource key beside list: see Bulk Import.
| Key | Default | Description |
|---|---|---|
search.enabled | true | false removes the box. |
search.prompt | “Search” | The placeholder. |
search.on_enter | false | Ask on Enter only. |
toolbar[].label | The button’s text. Required. | |
toolbar[].href | A path under the admin root, or an absolute URL. Required. | |
toolbar[].icon | none | An icon name from the shared set. |
toolbar[].permission | none | Hidden from a user who lacks it. |
toolbar[].primary | true renders it as the prominent action. Required. |
Send a row click anywhere
list:
row_click: "acme/orders/{id}/summary"
list:
row_click: "https://track.acme.com/parcels/{tracking_code}?order={id}"
| Pattern | Goes to |
|---|---|
acme/orders/{id}/summary | A path under the admin root. |
/shop/orders/{id} | A path on the site. |
https://... | A full address. |
| Placeholder | Fills in |
|---|---|
{id} | The record’s id. |
{column} | A column on the list, as stored, URL-encoded. |
A row with an empty value for a placeholder opens nothing. A record in the trash opens nothing.
ListConfig::new("orders", t!("Orders"), columns)
.row_click(RowClick::Url("acme/orders/{id}/summary".into()));
Name a column
Columns are a map. The key is the name, and they render in the order written:
columns:
title: {}
created_at: { type: datetime }
A missing label is made from the key: created_at becomes “Created at”. It
is still translatable, and lat i18n extract finds it, as it finds the label
of every entry under a column’s labels.
Set a column’s keys
| Key | Default | Description |
|---|---|---|
label | from the key | The header. |
type | text | The column type. Every type: List Columns. |
sortable | true | The header sorts. Empty values come last either way. |
invisible | false | Hidden until the user picks it from the column chooser. |
width | shared | A CSS width, 10% or 120px. |
align | left, center, right. | |
permission | none | A user without it does not see the column; it is then not queried, sorted, searched, picked or exported for them. |
searchable | text columns | Whether the search box looks in this column. |
labels | none | What a stored value reads as: [{ value: login_success, label: Signed in }]. A value not listed shows as stored. |
editable | false | The cell is the form field’s control, saved on change. The field must be on the resource’s form. |
related | none | The record under the list’s related the column is read from. |
Show a column of a related record
# descriptors/authors.yaml
list:
related:
profile: { entity: profiles, foreign_key: author_id }
address: { entity: addresses, belongs_to: address_id }
columns:
name: {}
city: { related: address }
bio: { related: profile, sortable: false }
ListConfig::new(
"authors",
t!("Authors"),
vec![
ListColumn::new("name", t!("Name")),
ListColumn::new("city", t!("City")).related("address"),
],
)
.related("address", RelatedRecord::belongs_to("addresses", "address_id"));
The key is the related table’s column. The column sorts, searches and exports
as the list’s own do. related takes the keys of a form’s
related.
A key the framework does not know is refused with its line; lat doctor
names it without a build.
Filters
A filter narrows the list to rows matching a value the user picks. Only a value a declared filter accepts reaches the query.
list:
filters:
status: { type: select, options: [{ value: draft, label: Draft }, { value: live, label: Live }], default_value: live }
featured: { type: boolean }
author: { type: text }
views: { type: number }
created_at: { type: date, permission: acme.blog.audit }
| Key | Default | Description |
|---|---|---|
label | from the key | The control’s label. |
type | text | boolean, select, text, number or date. |
options | A select filter’s choices: a list of { value, label }, or the name of an option source. Required for select. | |
depends_on | none | On a select with a source: the filters whose values the source reads. See select. |
default_value | none | Applied when the request names no value for this filter: the screen opens already narrowed. Clearing it is still “no filter”. |
permission | none | A user without it does not see the filter, and its default is not applied. |
A key written bare (author:) is a text filter with every default.
Narrow by a range or a related record
list:
related:
author: { entity: authors, belongs_to: author_id }
filters:
views_min: { label: Views at least, type: number, column: views, match: at_least }
views_max: { label: Views at most, type: number, column: views, match: at_most }
author_city: { label: Author's city, type: text, column: city, related: author }
| Key | Default | Description |
|---|---|---|
column | the filter’s key | The column compared, so two filters narrow one column. |
match | equals | On a number filter: equals, at_least or at_most. |
related | none | A record under the list’s related; the filter compares its column. |
Pick a scope type
| Type | The value reaches the query as |
|---|---|
boolean | 1 or 0: rows where the column is true or false. |
select | A declared value, matched exactly; any other value is dropped. |
text | A substring match, folded the way the search box folds. |
number | A whole number, matched exactly. |
date | A YYYY-MM-DD day; a date column and a stored timestamp both answer. |
Each type, with its example, is on Filter Scopes.
Declare a filter from code
use laterite_admin::list::{FilterOption, ListFilter};
let status = ListFilter::select("status", "Status", vec![
FilterOption::new("draft", "Draft"),
FilterOption::new("live", "Live"),
]).default_value("live");
let created = ListFilter::date("created_at", "Created").require("acme.blog.audit");
| Constructor | Type |
|---|---|
ListFilter::boolean(field, label) | boolean |
ListFilter::select(field, label, options) | select |
ListFilter::select_from(field, label, source) | select, its choices from an option source; .depends_on([..]) names the filters it follows. |
ListFilter::text(field, label) | text |
ListFilter::number(field, label) | number |
ListFilter::date(field, label) | date |
ListFilter::of(field, label, type) | Any declared type, with no options. |
| Method | Sets |
|---|---|
.column(name) | column |
.at_least(), .at_most() | match |
.related(name) | related |
.default_value(value) | default_value |
.require(permission) | permission |
Carry a filter in a URL
/admin/posts?f_status=draft&f_featured=1&q=launch&sort=created_at&dir=desc
| Parameter | Value |
|---|---|
f_<name> | The filter’s value. |
q | The search. |
sort, dir | The sort column and asc or desc. |
The export link carries the same parameters and downloads the list the screen shows.
Trees and Reordering
A list keeps its rows in an order of their own, shows them as a tree on a parent column, or both.
Reorder rows
list:
reorder: true
list:
reorder: { column: position }
ListConfig::new("pages", "Pages", columns).reorder("position")
| Key | Default | Does |
|---|---|---|
reorder | off | true keeps the order in sort_order; { column: position } names the column. An integer column, not null, default 0. |
reorder.column | sort_order | The column holding each row’s position. |
The list opens in that order with a grip to drag and Move up / Move down on
every row; a sorted, searched or filtered view shows neither. A has-many
section’s list takes the same key; see
Related Records.
Show rows as a tree
list:
tree: true
list:
tree: { parent_key: folder_id, source: acme.folders }
use laterite_admin::list::TreeConfig;
ListConfig::new("folders", "Folders", columns)
.tree(TreeConfig::new("folder_id").move_to("acme.folders"))
| Key | Default | Does |
|---|---|---|
tree | off | true reads the parent from parent_id; { parent_key, source } names the column and a picker source. |
tree.parent_key | parent_id | The column holding a row’s parent id, null at the top level. |
tree.source | none | A registered picker source over this entity. With it, every row offers “Move to”, which picks the new parent from the source or leaves it empty for the top level. A record never moves under itself. |
The list opens on the rows with no parent; a row with children expands in
place, or opens them as a page with scripting off. With reorder too, a move
stays among one parent’s children. A has-many section ignores tree.
Reach the routes
| Path | Method | Does |
|---|---|---|
/products/reorder | POST | Moves id with move=up or move=down, or before=<id> or after=<id>, and shows page again; parent names the branch under a tree. |
/products/7/move | GET, POST | The “Move to” form for record 7, and the move itself. |
Both answer an htmx request with the list region and a plain one with the page.
Writing a Column Type
A column type renders one kind of cell on any list that names it.
Implement the type
use laterite_admin::html::Markup;
use laterite_admin::list::{CellCx, CellVm, ColumnType, ColumnTypeReg};
struct Rating;
impl ColumnType for Rating {
fn view_key(&self) -> &'static str { "acme.rating" }
fn view_model(&self, cx: &CellCx<'_>) -> CellVm { /* ... */ }
fn render_default(&self, vm: &CellVm) -> Markup { /* ... */ }
}
| Method | Role |
|---|---|
view_key | The name a column’s type uses. A dotted vendor.name. |
view_model | The cell’s value as a view-model. |
render_default | The markup. |
option_keys | The keys the type reads from its column entry; any other key is refused at boot. |
check | Checks the column’s keys when the list is read; an error stops the boot. |
CellCx | Gives |
|---|---|
value | The stored value, as text. |
tz, locale | The display timezone and locale. |
options | The column’s entry, for the type’s own keys. |
option_str(key) | One of those keys, as text. |
field(column) | Another value in the row; field("id") is the record’s id. |
icon(name) | Inline SVG for an icon from the set. |
base() | The admin mount, for an address inside the admin. |
CellCx::new(value, tz, locale) | A context for a test, with with_options, with_row, with_icons, with_base. |
Register it
registry.add(ColumnTypeReg::new(Arc::new(Rating)));
columns:
rating: { type: acme.rating }
A taken key aborts the boot; so does a column naming a key nobody registered.
Export
A resource opts into exporting its list as a file; the download carries the rows the screen shows, minus the paging.
# descriptors/posts.yaml
list:
exportable: true
ListConfig::new("posts", "Posts", columns).exportable()
| Key | Default | Description |
|---|---|---|
exportable | false | Mounts /export under the resource and shows the export menu beside New. |
Choose the format
GET /admin/posts/export?format=csv&q=launch&sort=created_at&dir=desc&f_status=draft
| Format | Headed by | Content type |
|---|---|---|
csv (default) | The column labels, localized. | text/csv |
json | The column names. | application/json |
The file carries the columns the user can see and has chosen, the search, the
filters and the sort of the list it was offered from. An unknown format is
CSV.
Keep within the limit
| Limit | Value |
|---|---|
| Rows | 20 000 |
Past it the export is refused with a message asking to narrow the list.
Gate it
| Who | Gets |
|---|---|
A user holding the resource’s permission | The export menu and the route. |
A user without a column’s permission | A file without that column. |
| Anyone else | 403 Forbidden. |
Form Fields
Every built-in form field type, with the keys it reads. The keys every field
takes (label, span, rules, …) are on Form
Descriptor; a type of your own is Writing a
Field Type. A key a type does not read is refused,
naming the entry and the keys it accepts.
text
fields:
email: { type: text, input: email, placeholder: you@acme.test }
price: { input: number, min: 0, step: 0.01 }
site: { input: url, copy: true }
| Key | Default | Description |
|---|---|---|
input | text | text, email, tel, number, url, color. |
placeholder | none | The placeholder. |
counter | auto | auto, true, false. auto: with a max_length rule, shown once four fifths of it are used. |
min, max, step | none | A number input’s bounds and step. |
copy | false | A url input: a button copying the value. |
text is the type when none is written. An email input adds the email rule.
textarea
fields:
body: { type: textarea, rows: 8, placeholder: Write here, grow: false }
| Key | Default | Description |
|---|---|---|
rows | The height, in lines. | |
placeholder | none | The placeholder. |
grow | true | As tall as its text, from rows up to most of the window. |
counter | auto | As for text. |
richeditor
fields:
body: { type: richeditor, rows: 12, toolbar: [format, bold, italic, "|", link, image] }
| Key | Default | Description |
|---|---|---|
rows | The height, in lines. | |
placeholder | none | The placeholder. |
toolbar | every entry, in this order | A list from format, bold, italic, underline, strike, bullet_list, ordered_list, link, image, table, rule, undo, redo, ` |
Stores HTML kept to that set; an image from the library is linked to the record.
markdown
fields:
body: { type: markdown, rows: 12, preview: side }
terms: { type: markdown, preview: side, preview_url: acme/terms/preview }
| Key | Default | Description |
|---|---|---|
rows | The height, in lines. | |
placeholder | none | The placeholder. |
preview | tab | tab (or true): a Preview tab. side: the preview beside the text, rendered again as the text or any other field of the form changes. off (or false): none. |
preview_url | the built-in renderer | An endpoint of your own, under the admin (acme/terms/preview) or absolute (/render). It receives the form’s fields by POST, with text holding the editor’s content, and answers HTML, or a PDF to show the document itself. |
Stores the markdown as written; the site renders it with the
markdown filter.
codeeditor
fields:
styles: { type: codeeditor, language: css, rows: 20, wrap: true }
| Key | Default | Description |
|---|---|---|
language | text | text, html, css, javascript, json, yaml, markdown, jinja. |
rows | The height, in lines. | |
line_numbers | true | Numbers in the gutter. |
wrap | false | false: long lines scroll. |
placeholder | none | The placeholder. |
select
fields:
status: { type: select, options: [{ value: "", label: Any }, { value: draft, label: Draft }], search: auto }
| Key | Default | Description |
|---|---|---|
options | A list of { value, label, disabled, group }, or the name of an option source. group is the heading the choice sits under. | |
search | auto | auto, true, false. auto: past 10 choices, the dropdown is searched. An option with an empty value is what clearing chooses. |
radio
fields:
size: { type: radio, options: [{ value: s, label: Small }, { value: l, label: Large }] }
| Key | Default | Description |
|---|---|---|
options | A list of { value, label, note, disabled }, or the name of an option source. note is a second line under the label. |
checklist
Boxes in groups. The column holds the ticked values as a JSON array of text.
fields:
topics:
type: checklist
rules: [required] # a box must be ticked
options:
- { value: news, label: News }
- group: Sport
options:
- { value: football, label: Football, note: Every league }
- { value: cricket, label: Cricket }
select_all: auto
search: auto
expand: auto
| Key | Values | Default |
|---|---|---|
options | A list of { value, label, note } and { group, options }, nested to any depth, or the name of an option source. | None |
select_all | auto, true, false | auto: past 10 choices |
search | auto, true, false | auto: past 20 choices |
expand | auto, all, none | auto: past 10 choices in more than one group, a group with every box ticked or none starts closed and a group partly ticked starts open |
A value listed twice stops the boot, naming it.
taglist
Short texts typed one at a time. The column holds them as a JSON array of text.
fields:
aliases:
type: taglist
placeholder: "Another name"
rules: [required] # at least one tag
| Key | Values | Default |
|---|---|---|
placeholder | text | None |
Enter or a comma adds what is typed; a pasted list splits on commas and
lines. A tag typed twice is kept once. In a repeater row:
fields:
outlets:
type: repeater
fields:
name: {}
domains: { type: taglist }
lat.on('taglist:changed', function (detail) { console.log(detail.tags); });
switch
fields:
is_live: { type: switch, label: Published }
No keys. A yes or no over a boolean column.
section
fields:
delivery: { type: section, label: Delivery, help: Where and when the order ships. }
address: {}
ship_date: { type: date }
No keys. A heading over the fields after it, with help as the line beneath.
Nothing is stored or submitted. A trigger shows and hides the heading:
fields:
kind: { type: select, options: [{ value: post }, { value: event }] }
when: { type: section, label: When, trigger: { action: show, field: kind, condition: "value[event]" } }
starts: { type: date, trigger: { action: show, field: kind, condition: "value[event]" } }
date
fields:
published_at: { type: date }
No keys. The value must be a date.
password
fields:
token: { type: password, reveal: false }
| Key | Default | Description |
|---|---|---|
reveal | true | A button shows what was typed. |
sensitive
fields:
api_token: { type: sensitive }
A secret sealed under the application key before it is stored and shown as a mask. The eye shows the stored value and writes <entity>.reveal to the audit log (settings.reveal on a settings screen); typing replaces the value whole, and a blank or the mask submitted back leaves it as it is. The column is text; lat crypt rotate re-seals it after a key rotation.
fields:
service_key:
type: sensitive
file: true
accept: [.json, .p12]
max_size: 16kb
| Key | Default | Description |
|---|---|---|
file | false | The secret is an uploaded file, sealed in the same text column. |
accept | any | The extensions an upload may have. |
max_size | 64kb | The largest upload, in bytes or as 16kb, 1mb. At most 512kb. |
A sealed file shows its name, size and fingerprint, has no Reveal, and is replaced by choosing another.
use laterite_core::SealedFile;
let sealed = record.get("service_key").and_then(|v| v.to_text()).unwrap_or_default();
let key = SealedFile::open(&crypt, "service_key", &sealed)?;
let json: serde_json::Value = serde_json::from_slice(&key.bytes)?;
id
fields:
post_id: { type: id }
No keys. A record id held as a number, as a hidden input; a relation’s foreign key is one.
reference
fields:
author_id: { type: reference, source: acme.authors }
| Key | Default | Description |
|---|---|---|
source | A registered picker source. Required. |
The column holds the chosen id as a number.
repeater
fields:
links:
type: repeater
min_items: 1
max_items: 10
summary_field: label
fields:
label: {}
url: { input: url }
| Key | Default | Description |
|---|---|---|
fields | The row’s fields, a map like the form’s. Required. A field with no label shows its name. | |
min_items | 0 | The fewest rows: this many show from the start, and Remove is off at this count. |
max_items | none | The most rows: Add, the row’s add and Duplicate are off at this count. |
display | auto | auto, inline, list. auto: one field a row is compact; past 3 fields a row, rows collapse to the line naming them. |
summary_field | the first field | Which field names a collapsed row. |
expanded | false | List rows show open. |
prompt | Add | The Add button’s label. |
reorder | true | Each row moves up and down. |
duplicate | true | Each row copies into a new one beneath it. |
A row of one field is compact: one line a row, each with add and remove, and always at least one line.
fields:
aliases:
type: repeater
max_items: 5
fields:
name: { placeholder: "Another name" }
media
fields:
cover_id: { type: media, mode: image }
gallery: { type: media, max: 6 }
| Key | Default | Description |
|---|---|---|
mode | file | image offers images alone and shows thumbnails. |
max | 1 | How many files the field holds; 0 is no limit. |
public | false | The file is shown to people who are not signed in, so a private file is refused. |
The columns it writes and the links it keeps: Media Field.
List Columns
Every built-in column type. The keys every column takes (label, width,
labels, …) are on List Descriptor, and a type
of your own is Writing a Column Type.
text
columns:
title: { searchable: true }
The value as stored, or its entry under labels. The type when none is
written; the search box looks in it.
datetime
columns:
created_at: { type: datetime, align: right }
A date and time in the display timezone.
date
columns:
published_on: { type: date }
A date in the display timezone.
time
columns:
opens_at: { type: time }
A time of day in the display timezone.
boolean
columns:
is_live: { type: boolean, width: 80px }
| Value | Shown as |
|---|---|
1, true | Yes |
0, false, empty | No |
status_pill
columns:
status: { type: status_pill, labels: [{ value: draft, label: Draft }, { value: live, label: Live }] }
A pill coloured by the value, lowercased with anything but letters and digits
made a hyphen, and reading as its entry under labels.
link
columns:
website: { type: link, new_tab: true }
instagram: { type: link, icon: instagram, text: "@{value|handle}", new_tab: true }
order: { type: link, url: "acme/orders/{id}/edit", text: "Open {code}" }
| Key | Default | Description |
|---|---|---|
url | the value | The address, with {value} for the cell’s value, {id} for the record’s and {column} for another column on the list. A value filled in is URL-encoded. An address with no scheme and no leading / is under the admin. |
text | the value | What the link reads, with the same placeholders. "" shows the icon alone. |
| Placeholder | Fills in |
|---|---|
{value}, {id}, {column} | The value as stored |
{value|handle} | The last part of a link’s path, without @: band from https://social.acme/@band |
{value|host} | A link’s domain, without www.: acme.com |
icon | none |
new_tab | false |
format | the field’s |
| Case | Shown as |
|---|---|
http, https, mailto, tel or a / path | A link |
Any other address (javascript:, data:) | Text |
| A placeholder whose column is not on the list, or is empty | Text |
An empty value with no url | Nothing |
partial
A cell drawn by a template a module registers.
registry.add(PartialReg::new(
"acme.stock_level",
include_str!("../partials/stock_level.html"),
));
columns:
stock: { type: partial, path: acme.stock_level }
{# partials/stock_level.html #}
{% if value | int < 5 %}<b style="color:var(--danger)">{{ value }} left</b>
{% else %}{{ value }} in stock{% endif %}
<small>{{ record.sku }}</small>
| Key | Default | Description |
|---|---|---|
path | The partial’s registered name. Required; a name nobody registered stops the boot. |
| Variable | Holds |
|---|---|
value | The cell’s stored value, as text. |
record | Every column on the list by name, as text, and id. A column hidden from the list is not in it. |
column | The column’s keys from the list file. |
The template is MiniJinja. A value written with {{ }} is escaped as HTML;
the template’s own markup is not. The column sorts, searches and exports by
its stored value. A template that fails shows the value as text.
Filter Scopes
Every built-in filter type, with what it offers and what reaches the query.
The keys every filter takes (label, default_value, permission) are on
Filters.
boolean
filters:
featured: { type: boolean }
| Offers | Matches |
|---|---|
| Yes or no | Rows where the column is true (1) or false (0). |
select
filters:
status:
type: select
options: [{ value: draft, label: Draft }, { value: live, label: Live }]
default_value: live
country: { type: select, options: acme.countries }
state: { type: select, options: acme.states, depends_on: country }
| Key | Description |
|---|---|
options | The choices: a list of { value, label }, or the name of an option source. Required. |
depends_on | A filter, or a list of filters, whose values the source reads through OptionCx::values. When one changes, this filter’s choices are asked for again, and a value no longer offered is dropped. |
| Offers | Matches |
|---|---|
| One of the declared values | Rows equal to it. A value not declared is dropped. |
text
filters:
author: { type: text }
| Offers | Matches |
|---|---|
| A text box | Rows containing the text, folded the way the search box folds. |
number
filters:
views: { type: number }
| Offers | Matches |
|---|---|
| A number box | Rows equal to the whole number. Anything else is dropped. |
date
filters:
created_at: { type: date }
| Offers | Matches |
|---|---|
| A date picker | Rows on that YYYY-MM-DD day, whether the column holds a date or a timestamp. |
Icons
The framework ships 215 icons. Name one in any descriptor that
takes an icon: a settings item, a navigation entry, a resource.
SettingsItem::new("acme.blog", "Blog", fields).icon("newspaper")
An unknown name is refused when the application boots, with the nearest matches suggested.
Adding one that is not here
The set is a subset of upstream. A plugin registers what it needs:
registry.add(IconReg::new(
"map-pin-house",
include_str!("../assets/icons/map-pin-house.svg"),
));
It is namespaced to your module and referenced as
vendor.package:map-pin-house.
Flags
Fillable icons are closed shapes that read correctly filled, for a state
such as a favourited star. Filling is a render option, never part of the
name: there is no star-solid.
Mirrored icons flip under a right-to-left layout. A clock does not mirror; a chevron does.
Brands are drawn solid, in the brand’s own shape. A plugin’s brand mark
is registered with IconReg::new(name, svg).solid().
chrome (48)
| Name | ||
|---|---|---|
arrow-up-down | mirrors in RTL | |
check | ||
chevron-down | ||
chevron-left | mirrors in RTL | |
chevron-right | mirrors in RTL | |
chevron-up | ||
chevrons-left | mirrors in RTL | |
chevrons-right | mirrors in RTL | |
circle-alert | ||
circle-check | fillable | |
circle-help | ||
circle-x | ||
columns-3 | ||
copy | ||
download | ||
ellipsis | ||
ellipsis-vertical | ||
external-link | mirrors in RTL | |
eye | ||
eye-off | ||
funnel | ||
grip-vertical | ||
history | ||
info | ||
layout-dashboard | ||
layout-grid | ||
list | mirrors in RTL | |
loader-circle | ||
log-in | mirrors in RTL | |
log-out | mirrors in RTL | |
menu | ||
monitor | ||
moon | ||
panel-left | mirrors in RTL | |
pencil | ||
plus | ||
redo-2 | mirrors in RTL | |
refresh-cw | ||
save | ||
search | ||
settings | ||
sliders-horizontal | ||
sun | ||
trash-2 | ||
triangle-alert | ||
undo-2 | mirrors in RTL | |
upload | ||
x |
people (12)
| Name | ||
|---|---|---|
contact | ||
fingerprint | ||
id-card | ||
key | ||
lock | ||
lock-open | ||
shield | ||
shield-check | ||
user | ||
user-plus | ||
user-round | ||
users |
content (37)
| Name | ||
|---|---|---|
bold | ||
book-open | ||
bookmark | fillable | |
braces | ||
code | ||
file | ||
file-text | ||
files | ||
film | ||
flag | fillable | |
folder | ||
folder-open | ||
folder-plus | ||
heading | ||
heart | fillable | |
image | ||
images | ||
italic | ||
link | ||
list-ordered | mirrors in RTL | |
minus | ||
music | ||
newspaper | ||
notebook-pen | ||
notepad-text | ||
paperclip | ||
pin | fillable | |
quote | mirrors in RTL | |
square-pen | ||
star | fillable | |
strikethrough | ||
table | ||
tag | ||
tags | ||
type | ||
underline | ||
unlink |
communication (11)
| Name | ||
|---|---|---|
at-sign | ||
bell | fillable | |
bell-off | ||
bell-ring | ||
mail | ||
megaphone | ||
message-circle | ||
message-square | ||
phone | ||
rss | ||
send | mirrors in RTL |
commerce (25)
| Name | ||
|---|---|---|
badge-percent | ||
banknote | ||
briefcase | ||
building | ||
building-2 | ||
calculator | ||
chart-bar | ||
chart-line | ||
chart-pie | ||
coins | ||
credit-card | ||
gift | ||
landmark | ||
package | ||
percent | ||
receipt | ||
scale | ||
shopping-bag | ||
shopping-cart | ||
store | ||
ticket | ||
trending-down | mirrors in RTL | |
trending-up | mirrors in RTL | |
truck | ||
wallet |
time-place (12)
| Name | ||
|---|---|---|
alarm-clock | ||
calendar | ||
calendar-days | ||
clock | ||
compass | ||
globe | ||
home | ||
map | ||
map-pin | ||
map-pinned | ||
navigation | ||
timer |
technical (27)
| Name | ||
|---|---|---|
bluetooth | ||
bot | ||
bug | ||
camera | ||
cloud | ||
cloud-download | ||
cloud-upload | ||
cpu | ||
database | ||
git-branch | ||
hard-drive | ||
laptop | ||
mic | ||
plug | ||
printer | ||
qr-code | ||
server | ||
smartphone | ||
sparkles | ||
tablet | ||
terminal | ||
video | ||
wand-sparkles | ||
webhook | ||
wifi | ||
workflow | ||
zap |
objects (28)
| Name | ||
|---|---|---|
activity | ||
award | ||
blocks | ||
box | ||
boxes | ||
brush | ||
check-check | fillable | |
circle | fillable | |
component | ||
crown | ||
droplet | ||
flame | ||
gauge | ||
hammer | ||
layers | ||
layout-template | ||
leaf | ||
lightbulb | ||
paintbrush | ||
palette | ||
puzzle | ||
rocket | ||
square | fillable | |
square-check | fillable | |
target | ||
triangle | fillable | |
trophy | ||
wrench |
brands (15)
| Name | ||
|---|---|---|
apple | ||
discord | ||
facebook | ||
github | ||
google | ||
instagram | ||
pinterest | ||
soundcloud | ||
spotify | ||
telegram | ||
threads | ||
tiktok | ||
whatsapp | ||
x-twitter | ||
youtube |
Bulk Import
A resource’s records imported from a CSV, each row written through the resource’s form, one commit a row, with a report. Built into the admin.
Let a resource be imported into
# descriptors/products.yaml
import: true
import:
permission: acme.import_products
Resource::new("/products", "Products", list)
.form(form)
.permission("acme.manage_products")
.import(ImportConfig::new())
[backend]
storage = "storage"
fn register(&self, registry: &mut Registry) {
registry.add(DiskReg::new("private", Arc::new(LocalDisk::new("/srv/acme/private"))));
}
| Key | Default | Does |
|---|---|---|
import: true | off | Mounts the pages at /admin/products/import and shows an Import button beside the list’s export menu. |
import.permission | the resource’s | The permission a user needs to import. |
backend.storage | storage | The directory the uploaded file is kept under, in private, as a media record outside the library. |
DiskReg named private | none | Keeps the file on another disk. |
A resource declaring import needs a form and a permission; either missing
aborts boot naming the resource.
The delimiter is read off the file’s first line (comma, semicolon or tab) and can be set by hand. Files are read as UTF-8; a byte-order mark is accepted.
Start a run from code
use laterite_admin::import::{start, Duplicates, Match, RunSpec};
let products = ctx.form("/products").expect("the products resource");
let spec = RunSpec::new("/products", vec![Match::new(0, "sku"), Match::new(1, "name")])
.duplicates(Duplicates::update("sku"))
.media(payload_id);
let run = start(ctx.db(), products, actor, spec, disk.get(&path).await?).await?;
start records the run, detaches the work and returns the run’s id. The
request that started it may end; the rows keep being written.
| Option | Default | Does |
|---|---|---|
RunSpec::new(resource, matches) | The resource’s path as its descriptor declares it, and the column matches. | |
Match::new(column, field) | File column column (from 0) fills field. A column may fill several fields. | |
.duplicates(Duplicates::skip(key)) | none | A row whose key is already there is passed over and noted. |
.duplicates(Duplicates::update(key)) | none | A row whose key is already there updates that record; fields the file does not carry keep their values. |
.keep_blank(bool) | true | On an update, a blank matched cell leaves the record’s value as it is. false clears the field. |
.dry_run(bool) | false | Nothing is written; the counts say what an import would do. |
.first_row_titles(bool) | true | The first row names the columns and is passed over. |
.delimiter(u8) | b',' | The byte between values. |
.titles(vec) | none | The file’s titles; a later file with the same titles is proposed this matching. |
.media(id) | none | The stored payload’s record, kept on the run. |
start returns RunError::Spec for a match naming a field the form lacks, no
matches, or a duplicates key no column feeds. A blank row is passed over.
Poll a run
use laterite_admin::import::{find, Status};
let run = find(ctx.db(), id).await?.expect("a run");
match run.status {
Status::Queued => "waiting for a worker".to_string(),
Status::Running => format!("{} rows so far", run.processed),
Status::Done => format!("{} created, {} updated", run.created, run.updated),
Status::Failed => run.failure.unwrap_or_default(),
}
| Field | Meaning |
|---|---|
status | Queued (pushed, no worker has taken it), Running, Done, or Failed (the run itself stopped; failure says why). A run whose worker stopped is failed by the queue after queue.retry_after_seconds. |
processed, created, updated, skipped, errors | Row counts. On a dry run, what an import would do. |
notes | One per message: row (the line in the file), kind (Error or Skipped), field, message (a Text, localized where it renders). |
spec | What ran, dry_run included. |
resource, media_id, actor_label, started_at, finished_at | What ran, as recorded. |
A refused row is a note; the next row still runs.
Writing a Plugin
lat make:plugin scaffolds a plugin crate; lat plugin add installs it.
lat make:plugin acme.blog # blog-plugin/: Cargo.toml, src/lib.rs
lat make:plugin acme.blog --admin # adds src/admin/
lat plugin add ./blog-plugin
| Argument | Description |
|---|---|
<ID> | The module id, vendor.name. The crate is vendor-name. |
--path <PATH> | Where to create it. Default the current directory. |
--admin | Scaffold the admin half: descriptors, screens, settings. |
Mark the crate
Name its module, and declare the framework by version:
[package.metadata.laterite]
plugin = "acme.blog"
[dependencies]
laterite-core = "0.12"
laterite-admin = "0.12"
The dependency requirement is the compatibility statement. lat plugin add
refuses a plugin built for another Laterite:
$ lat plugin add ../acme-legacy
Error: acme-legacy needs laterite-core ^0.2, and this application is on 0.5.0.
Never declare the framework by path. An application on a local checkout maps
it with [patch.crates-io], which lat new writes in development mode.
Use the framework’s crates
use laterite_core::sea_query::{self, Alias, Expr, Iden, Query};
use laterite_core::serde_json::json;
use laterite_core::{minijinja, sqlx};
use laterite_admin::axum::Router;
| Crate | Reach it at |
|---|---|
sqlx | laterite_core::sqlx |
sea-query | laterite_core::sea_query (with use, #[derive(Iden)] works) |
serde_json | laterite_core::serde_json |
minijinja | laterite_core::minijinja |
axum | laterite_admin::axum |
serde | a dependency of the plugin’s own: serde = { version = "1", features = ["derive"] } |
lat plugin sync, lat plugin check and lat doctor read the application’s dependency graph:
$ lat plugin sync
Dependencies:
error sea-query is built in 2 versions (0.31.1 for acme-maps; 0.32.7 for the framework); values of one do not fit the other, so these cannot exchange them. Move the plugin onto the framework's version.
warn acme-maps depends on sea-query itself; reach it through `laterite_core::sea_query` so a version change on either side cannot split its types
note 44 other crate(s) are built in more than one version, none crossing a plugin boundary (`lat plugin check` lists them)
| Finding | Level |
|---|---|
A crate whose types cross the boundary (sqlx, sea-query, serde_json, minijinja, axum, laterite-*) in two versions | error |
| Two plugins, or a plugin and the framework, linking the same native library | error |
| A plugin listing a re-exported crate itself | warning |
| Any other crate in two versions | note |
Expose the module
At the crate root:
use laterite_core::{migration_set, BootCx, CoreResult, MigrationSet, Module, ModuleId, Registry};
migration_set! {
module_id: "acme.blog",
}
pub fn module() -> Box<dyn Module> {
Box::new(Plugin)
}
pub struct Plugin;
impl Module for Plugin {
fn id(&self) -> ModuleId {
ModuleId::new("acme.blog")
}
fn migrations(&self) -> MigrationSet {
migrations()
}
fn register(&self, registry: &mut Registry) {
// registry.add_resource(..);
// registry.add_permission(..);
// registry.add_settings(..);
}
async fn boot(&self, cx: &BootCx<'_>) -> CoreResult<()> {
// A sweep, a seed or a check, with cx.db and cx.registry.
Ok(())
}
}
| Method | Runs | Description |
|---|---|---|
migrations | Before register, in dependency order. | Applies the module’s own migrations. See Migrations. |
register | Once every module has migrated. | Contributes resources, settings models, permissions, menu entries, hooks. |
boot | Once every module has registered, before anything is served. | Anything that needs the database and the whole registry. An error quarantines the plugin. |
Add a resource
lat make:resource article --field title:text --field body:text --field published:boolean
Scaffolds the entity’s migration, schema, store and admin screen, mounted at
/articles. Field types: text, integer, boolean, datetime. See
Resource Features and Hooks. --source content/articles
keeps the records as files; see Records in Files.
Installing Plugins
A plugin is a crate compiled into the application. Installing one records it and rebuilds.
| State | Where | Changing it costs |
|---|---|---|
| Which plugins are compiled in | plugins/plugins.toml | a rebuild |
| Which of them are enabled | the database | a restart |
Add one
$ lat plugin add ../acme-blog-plugin
$ lat plugin add https://github.com/acme/blog-plugin
$ cargo build
A checkout outside the project is linked into plugins/, not copied. --as <folder> picks the folder name.
A plugin added from a git URL is vendored: its files are copied in without their .git folder, and source in the list records the URL.
In a static website (see Static Website) the first lat plugin add writes the site’s Cargo project, and only a plugin whose marker says static = true is accepted.
Edit the list
# plugins/plugins.toml
[[plugin]]
path = "acme-blog"
[[plugin]]
path = "acme-blog"
source = "https://github.com/acme/blog-plugin"
| Command | Description |
|---|---|
lat plugin add | Records a plugin and syncs. |
lat plugin remove | Drops the entry. --delete removes the folder; a link only loses its link. |
lat plugin sync | Regenerates plugins-manifest/ from the list. Run after editing by hand. |
lat plugin list | Prints the plugins the application compiles in. |
lat plugin check | Checks each installed plugin against the expected layout. |
lat doctor | Checks the list and the manifest agree. |
Two entries resolving to one crate are refused.
Enable and disable
Settings → Plugins turns a compiled-in plugin off without a rebuild. The change applies at the next start: a disabled plugin’s migrations do not run, it contributes nothing, and anything depending on it is skipped. Its tables stay.
Resource Features and Hooks
A module mounts routes of its own under any resource that opts in, or changes another module’s resource before it mounts.
Mount a feature under a resource
use laterite_admin::axum::routing::get;
use laterite_admin::axum::Router;
use laterite_admin::routes::{ResourceFeature, ResourceFeatureReg, ResourceInfo, RouteCtx};
struct Archive;
impl ResourceFeature for Archive {
fn mount(&self, ctx: &RouteCtx, resource: &ResourceInfo) -> Router {
let form = resource.form.clone();
Router::new().route("/", get(move || async move { form.entity().to_string() }))
}
}
registry.add(ResourceFeatureReg::new("archive", Arc::new(Archive)));
# descriptors/products.yaml
archive: true
| Field | Meaning |
|---|---|
resource.path | The resource’s path as declared, relative to the admin root (/products). |
resource.base_path | Where its list mounted (/admin/products). |
resource.label | Its menu label. |
resource.permission | The permission the feature’s routes are gated by. |
resource.form | Its form, to write records through. |
The routes mount at {base_path}/{key} behind the permission. A descriptor
declaring a key nobody registered aborts boot naming the resource. The admin
knows the import key; a new key needs the admin to carry it.
Change another module’s resource
registry.add_resource_hook(ResourceHook::new("/acme/blog/posts", |mut resource| {
resource.list.columns.push(ListColumn::new("reviewed", "Reviewed").boolean());
resource
.relation(RelationConfig::has_many("notes", "Note", "post_notes", "post_id", notes_list, notes_form))
.menu(Placement::new().under("acme.content"))
}));
| Key | Does |
|---|---|
target | The resource’s path as it mounts: /posts for an application’s, /acme/blog/posts for a plugin’s under its module base. One nobody declared aborts boot. |
| The closure | Takes the resource as declared, returns it changed. Anything the builders set: columns, fields, relations, import, the palette source, the menu placement. |
| Order | Hooks run in module order, before the resource mounts; each sees the previous one’s result. |
Console Commands
A module adds a command to the application. lat <name> runs it from the
project, after the application has booted.
Register a command
use std::sync::Arc;
use laterite_core::command::{Command, CommandCx, CommandError, CommandReg};
use laterite_core::t;
struct Greet;
#[async_trait::async_trait]
impl Command for Greet {
async fn run(&self, cx: &CommandCx<'_>, args: &[String]) -> Result<(), CommandError> {
let name = args.first().ok_or("usage: greet <name>")?;
println!("Hello {name}, from {}", cx.storage_dir());
Ok(())
}
}
impl Module for AcmeBlog {
fn register(&self, registry: &mut Registry) {
registry.add(CommandReg::new("greet", t!("Greet someone"), Arc::new(Greet)));
}
}
lat greet Ada
lat help-app
CommandReg::new | Description |
|---|---|
name | The word that runs it: lowercase letters, digits and hyphens. |
about | One line in lat help-app. |
command | What runs. |
CommandCx | Gives |
|---|---|
db() | The application’s database, migrated. |
registry() | Every module’s registrations. |
storage_dir() | backend.storage. |
Parse arguments
use clap::Parser;
#[derive(Parser)]
struct Args {
name: String,
#[arg(long)]
loud: bool,
}
async fn run(&self, cx: &CommandCx<'_>, args: &[String]) -> Result<(), CommandError> {
let args = Args::try_parse_from(std::iter::once("greet".to_string()).chain(args.iter().cloned()))?;
println!("{}", if args.loud { args.name.to_uppercase() } else { args.name });
Ok(())
}
| Case | Result |
|---|---|
run returns an error | The message is printed and the binary exits non-zero. |
A name the binary answers itself (serve, admin, routes, seed, build, publish, queue, schedule, help) | The start aborts. |
| Two modules register one name | The start aborts. |
| An unknown name | The error lists every command. |
The application’s main must call Bootstrap::run, as lat new writes it.
Abilities
An ability is one act a module declares by name, with a typed input and a permission, for any caller to run as the signed-in person.
Declare an ability
use laterite_admin::ability::{Ability, AbilityCx, AbilityError, AbilityHandler, Effect, Link, Outcome};
use laterite_admin::AdminRegistry;
use laterite_core::serde_json::Value;
use laterite_core::t;
use std::sync::Arc;
#[derive(serde::Deserialize, schemars::JsonSchema)]
struct AddLead {
/// The person's full name.
name: String,
/// A phone number with its country code.
phone: Option<String>,
}
struct AddLeadHandler;
#[laterite_core::strata::async_trait]
impl AbilityHandler for AddLeadHandler {
async fn run(&self, cx: &AbilityCx<'_>, input: Value) -> Result<Outcome, AbilityError> {
let lead: AddLead = laterite_core::serde_json::from_value(input)
.map_err(|e| AbilityError::invalid(e.to_string()))?;
let id = acme::leads::add(cx.db(), &lead.name, lead.phone.as_deref(), cx.actor())
.await
.map_err(|e| AbilityError::Failed(e.to_string()))?;
Ok(Outcome::new(t!("Added the lead."))
.link(Link::new(lead.name, format!("/admin/acme/crm/leads/{id}/edit"))))
}
}
fn register(&self, registry: &mut laterite_core::Registry) {
registry.add_ability(
Ability::new("acme.crm.add_lead", t!("Add a lead"), Arc::new(AddLeadHandler))
.describe(t!("Adds a person to the leads list."))
.permission("acme.crm.leads.create")
.input::<AddLead>()
.sensitive(["phone"])
.effect(Effect::Create),
);
}
| Method | Sets | Default |
|---|---|---|
new(code, label, handler) | the dotted code with the module’s id first, the name people see, the code behind it | required |
describe | what it does and when to use it, for a caller choosing among abilities | none |
group | the shelf it sits on in a catalogue | the code without its last segment |
permission | the permission a person needs to see and run it | open to every operator |
input::<T>() | the input as a type deriving schemars::JsonSchema | no input |
input_schema(value) | the input as a JSON Schema object | no input |
effect | what running it does | Effect::Run |
untrusted() | marks the result as carrying text written by people outside the panel | trusted |
sensitive([..]) | input fields left out of the audit entry | none |
| Effect | Meaning |
|---|---|
Read | answers a question and changes nothing |
Create | adds a record |
Update | changes a record |
Delete | removes a record |
Send | sends something to a person outside the panel |
Run | any other change: publishing, importing, a rebuild |
An ability with an effect other than Read names a permission. A doc comment
on an input field is that field’s description in the schema.
Say what it would do
use laterite_admin::ability::{Draft, Preview};
async fn preview(&self, cx: &AbilityCx<'_>, input: &Value) -> Result<Preview, AbilityError> {
let version = acme::documents::draft_version(cx.db(), input).await?;
Ok(Preview::new(t!("Publishes the draft of Terms of Use."))
.record(Link::new(version.title, version.href))
.count(1))
}
| Method | Sets |
|---|---|
Preview::new(summary) | the act in a sentence |
record(link) | a record the act touches |
count(n) | how many records it touches |
draft(Draft::new(path, id, values)) | a resource’s form, filled in, for the person to save |
Answer from the handler
| Return | When |
|---|---|
Ok(Outcome::new(message)) | it ran; add .link(..) for records and .data(..) for a result as JSON |
Ok(Outcome::new(message).go(href)) | it ran, and the person is taken to href, a path on the site |
Err(AbilityError::Refused(text)) | it declined, with a reason the person reads |
Err(AbilityError::invalid(message)) | the input is wrong in a way the schema cannot state |
Err(AbilityError::Failed(message)) | it broke; the message goes to the log |
AbilityCx gives db(), ctx(), user() and actor(). Pass actor() to
FormHandle::create and FormHandle::update, and to AuditEntry::new.
Run an ability
use laterite_core::serde_json::json;
let abilities = ctx.abilities();
for ability in abilities.for_user(&user) {
println!("{} ({})", ability.code(), ability.effect_kind().as_str());
}
let found = abilities.search(&user, "add a lead", 5);
let preview = abilities
.preview(&user, "acme.crm.add_lead", &json!({ "name": "Asha Rao" }), None)
.await?;
let outcome = abilities
.run(&user, "acme.crm.add_lead", json!({ "name": "Asha Rao" }), Some("acme.assistant"))
.await?;
| Method | Answers |
|---|---|
for_user(&user) | every ability the person may run |
get(&user, code) | one ability, when the person may run it |
search(&user, words, limit) | the abilities matching the words, best first |
preview(&user, code, &input, channel) | the handler’s Preview |
run(&user, code, input, channel) | the handler’s Outcome |
channel names what acts for the person (acme.assistant), or None. The
Audit Log shows it under Through.
| Error | Cause |
|---|---|
AbilityError::Unknown(code) | no ability has the code, or the person lacks its permission |
AbilityError::Invalid(faults) | the input does not fit the schema; one message per fault |
A run with an effect other than Read writes an ability.run audit entry.
Act for a person
use laterite_admin::ability::Confirm;
let abilities = ctx.abilities();
const CHANNEL: &str = "acme.assistant";
for (ability, confirm) in abilities.offered(&user).await? {
println!("{} ({})", ability.code(), confirm.as_str());
}
match abilities.confirm(&user, "acme.crm.add_lead").await? {
Confirm::Auto => {
abilities.run(&user, "acme.crm.add_lead", input, Some(CHANNEL)).await?;
}
_ => {
let preview = abilities
.preview(&user, "acme.crm.add_lead", &input, Some(CHANNEL))
.await?;
// Show the preview; run once the person agrees.
}
}
| Answer | Means | Default for |
|---|---|---|
Confirm::Auto | run without asking | Effect::Read |
Confirm::Ask | show the preview, run when the person agrees | every other effect |
Confirm::Off | not offered: confirm, preview and run answer AbilityError::Unknown | Effect::Delete, Effect::Send |
A call with channel set to None is the person themself and is not asked.
use laterite_admin::ability::{Confirm, OwnPolicy, PanelPolicy, PolicyRule};
use laterite_admin::settings::store;
store::save(ctx.db(), &PanelPolicy {
rules: vec![
PolicyRule::new("effect:delete", Confirm::Ask),
PolicyRule::new("acme.crm", Confirm::Ask),
PolicyRule::new("acme.crm.add_lead", Confirm::Auto),
],
}).await?;
store::save_for(ctx.db(), user.user.id, &OwnPolicy {
rules: vec![PolicyRule::new("acme.crm.add_lead", Confirm::Ask)],
}).await?;
| Rule | Covers | Wins over |
|---|---|---|
acme.crm.add_lead | that ability | every other rule |
acme.crm | every ability whose code starts acme.crm. | a shorter start, an effect |
effect:create | every ability with that effect | the default |
| Set by | Where | Reach |
|---|---|---|
An administrator holding backend.manage_abilities | Settings, Abilities (PanelPolicy) | the furthest anyone goes |
| Each person | Preferences, Acting for me (OwnPolicy) | tighter than the panel’s rule, or as loose as it and no looser |
A run through a channel records its answer as confirm in the audit entry.
Offer a resource’s records
entity: posts
path: /posts
title: Posts
permission: acme.posts.manage
abilities:
describe: Blog posts. A post has a title, a body in markdown and a publish date.
update: false
hide: [internal_notes]
use laterite_admin::records::RecordAbilities;
Resource::new("/posts", "Posts", list)
.abilities(RecordAbilities::new().describe(t!("Blog posts.")).hide(["internal_notes"]));
| Key | Sets | Default |
|---|---|---|
abilities: false | keeps the resource out of every record ability | offered |
describe | what the records are, for a caller choosing where to look | none |
create | a new record may be drafted | true, where the list is creatable |
update | a change may be drafted | true |
delete | a record may be deleted | true, where the list is deletable |
hide | fields and columns kept from a caller | none |
untrusted | the records carry text written by people outside the panel | false |
| Ability | Input | Answers |
|---|---|---|
backend.records.kinds | resource (optional) | the kinds open to the person; one kind with its fields, columns, filters and sorts |
backend.records.find | resource, search, filters, sort, dir, limit | matching rows with their ids, 25 at most |
backend.records.open | resource, search, filters, sort, dir | the list’s address with all of it set, as Outcome::go |
backend.records.read | resource, id | one record’s field values |
backend.records.create | resource, values | preview: the filled form as a Draft; run: the new id |
backend.records.update | resource, id, values | preview: the changed form as a Draft; run: the id |
backend.records.delete | resource, id | preview: the record named; run: the id, moved to the trash on a soft_delete resource |
{ "resource": "/posts", "filters": { "status": "live", "views_min": 1000 }, "sort": "views", "dir": "desc" }
filters names the list’s own filters, the ones the
person may use. resource is the resource’s path. Each ability asks for the resource’s
permission, and a create or an update for its permissions.create or
permissions.update, and a delete for permissions.delete. password and sensitive fields are never read or set.
Act for a person in your own writes
use laterite_core::Actor;
let actor = Actor::from(&user).through("acme.assistant");
form.create(values, &actor).await?;
Actor::channel() reads it back in a model listener.
Surfaces
A surface is a screen describing itself to a caller: its controls, the parts inside it and what each part does.
Describe a component
use laterite_admin::ability::{AbilityCx, AbilityError, Outcome};
use laterite_admin::surface::{Control, Part, Request, Surface, READ, SHOW};
use laterite_admin::AdminRegistry;
use laterite_core::serde_json::json;
use laterite_core::{t, Text};
use std::sync::Arc;
struct Overview;
#[laterite_core::strata::async_trait]
impl Surface for Overview {
fn path(&self) -> &str {
"/acme/overview"
}
fn label(&self) -> Text {
t!("Overview")
}
fn permission(&self) -> Option<&str> {
Some("acme.reports.view")
}
async fn parts(&self, _cx: &AbilityCx<'_>) -> Result<Part, AbilityError> {
Ok(Part::new("overview", t!("Overview")).act(SHOW).part(
Part::new("orders_by_day", t!("Orders by day"))
.describe(t!("How many orders arrived each day."))
.control(
Control::new("range", t!("Period"), "date_range")
.value(json!({ "from": "2026-10-01", "to": "2026-10-31" })),
)
.control(Control::new("group_by", t!("Group by"), "select").values(["day", "week"]))
.act(READ),
))
}
async fn act(&self, cx: &AbilityCx<'_>, request: &Request) -> Result<Outcome, AbilityError> {
if request.act == SHOW {
return Ok(Outcome::new(t!("Opened the overview.")).go("/admin/acme/overview"));
}
let from = request.set["range"]["from"]
.as_str()
.ok_or_else(|| AbilityError::invalid("set/range: give `from` and `to`"))?;
let points = acme::orders::by_day(cx.db(), from, request.text("group_by")).await?;
Ok(Outcome::new(t!("The orders by day.")).data(json!({ "points": points })))
}
}
fn register(&self, registry: &mut laterite_core::Registry) {
registry.add_surface(Arc::new(Overview));
}
| Method | Answers | Default |
|---|---|---|
path | where the screen is under the admin root; it names the surface | required |
label | what a person calls the screen | required |
describe | what the screen is for | none |
permission | the permission a person needs to see it | every signed-in person |
parts | the screen as this person sees it | required |
act | sets the controls a request names and does its act | required |
Build the description
Part | Sets |
|---|---|
Part::new(name, label) | the name a caller uses, the name a person reads |
describe(text) | what the part shows |
control(control) | something a caller sets |
part(part) | a component inside this one |
act(name) | something the part does: SHOW, READ, or a word of its own |
Control | Sets |
|---|---|
Control::new(name, label, kind) | the name, the label, and text, number, boolean, date, date_range, select or a word of its own |
describe(text) | what it narrows or changes |
values([..]) | the fixed set of values it takes |
value(value) | what it is set to now |
| Act | Does |
|---|---|
SHOW (show) | answers Outcome::go with the screen’s address, the controls set |
READ (read) | answers Outcome::data with what the part holds |
Read a request
let part: &[String] = &request.part; // ["orders_by_day"]
let act: &str = &request.act; // "read"
let grouping = request.text("group_by"); // Some("day")
let range = &request.set["range"]; // { "from": .., "to": .. }
| Field | Holds |
|---|---|
part | the names from the surface down to the part; empty for the surface itself |
act | an act that part lists |
set | the controls to set, by name; each one the part lists |
Return AbilityError::invalid("set/range: ..") for a value the control does
not take.
Call a surface
use laterite_core::serde_json::json;
let abilities = ctx.abilities();
let screens = abilities.run(&user, "backend.screens.list", json!({}), None).await?;
let described = abilities
.run(&user, "backend.screens.describe", json!({ "screen": "/acme/overview" }), None)
.await?;
let read = abilities
.run(&user, "backend.screens.act", json!({
"screen": "/acme/overview",
"part": "orders_by_day",
"act": "read",
"set": { "range": { "from": "2026-11-01", "to": "2026-11-15" }, "group_by": "day" }
}), None)
.await?;
| Ability | Input | Answers |
|---|---|---|
backend.screens.list | none | every screen open to the person: screen, label, describe |
backend.screens.describe | screen | its controls, parts and acts |
backend.screens.act | screen, part (names joined with /), set, act | the act’s Outcome |
{
"screen": "/acme/overview", "name": "overview", "label": "Overview", "acts": ["show"],
"parts": [{
"name": "orders_by_day", "label": "Orders by day", "acts": ["read"],
"controls": [
{ "name": "range", "label": "Period", "kind": "date_range",
"value": { "from": "2026-10-01", "to": "2026-10-31" } },
{ "name": "group_by", "label": "Group by", "kind": "select", "values": ["day", "week"] }
]
}]
}
Add a surface while mounting
impl Screen for Sales {
fn mount(&self, ctx: &RouteCtx) -> Router {
let board = Arc::new(self.board());
ctx.add_surface(board.surface("/acme/sales", t!("Sales")));
Router::new().nest_service("/board", board.routes(ctx))
}
}
| Call | When |
|---|---|
registry.add_surface(surface) | in register, for a surface known then |
ctx.add_surface(surface) | in Screen::mount, for one built there; the same path replaces |
board.surface(path, label) | a board and its widgets as a surface |
Lists
Every resource that offers record abilities is a surface
named by its path.
| Control | Is |
|---|---|
search | the list’s search |
| each filter by its key | that filter, with its values for a select |
sort, dir | a sortable column, and asc or desc |
{ "screen": "/posts", "act": "show", "set": { "status": "live", "views_min": 1000, "sort": "views", "dir": "desc" } }
Settings pages
Every settings page with fields is a surface at its page’s path, behind the page’s permission.
| Control | Is |
|---|---|
| each field by its name | the field, with its value as stored; a person’s own for a per-person page |
| Act | Answers |
|---|---|
show | the page’s address |
read | the stored values by field name |
A password or sensitive field is never named. A request that sets a
control is refused: a setting is changed on its page.
Palette Modes
A palette mode is a tab in the command palette (Ctrl+K, Cmd+K) that posts what a person types to a route of yours and shows the markup it answers.
Add a mode
use laterite_admin::palette::PaletteMode;
use laterite_admin::AdminRegistry;
use laterite_core::t;
fn register(&self, registry: &mut laterite_core::Registry) {
registry.add_palette_mode(
PaletteMode::new("acme.lookup", t!("Look up"), "/acme/lookup/ask")
.placeholder(t!("An order number"))
.prefix('#')
.permission("acme.orders.view")
.live(),
);
}
| Method | Sets | Default |
|---|---|---|
new(code, label, path) | the dotted code with the module’s id first, the tab’s name, the route under the admin root | required |
placeholder | the hint in the empty box | none |
prefix | a character that, typed first, switches to the mode | none |
permission | the permission a person needs to be offered the mode | every signed-in person |
live() | posts as the person types | posts on Enter |
Answer the palette
use axum::{response::Html, routing::post, Form, Router};
#[derive(serde::Deserialize)]
struct Asked {
q: String,
}
async fn ask(Form(asked): Form<Asked>) -> Html<String> {
let number: u64 = asked.q.trim().parse().unwrap_or_default();
Html(format!(
r#"<ul class="lat-palette__list" role="listbox">
<li><a class="lat-palette__hit" role="option" href="/admin/acme/orders/{0}">
<span class="lat-palette__label">Order {0}</span>
<span class="lat-palette__hint">Open</span>
</a></li>
</ul>"#,
number
))
}
fn mount(&self) -> Router {
Router::new().route("/ask", post(ask))
}
The route is a screen mounted at the mode’s path. The
post carries the form field q.
| Markup | Does |
|---|---|
class="lat-palette__list" with lat-palette__hit links | a result list the arrow keys walk and Enter opens |
class="lat-palette__empty" | a line for no result |
class="lat-palette__card" | a form, a card or a result with a title |
data-palette-raise on the answer’s root | moves the palette to the top of the screen and widens it |
data-palette-focus on one control | takes the focus when the answer arrives |
hx-target="closest .lat-palette__canvas" | swaps the next answer into the same panel |
<form class="lat-palette__card" data-palette-raise
hx-post="/admin/acme/lookup/refund"
hx-target="closest .lat-palette__canvas" hx-swap="innerHTML">
<h2 class="lat-palette__title">Refund order 1042</h2>
<p class="lat-palette__summary">Returns 40.00 USD to the card.</p>
<div class="lat-actions">
<button class="lat-btn lat-btn--danger" type="submit" data-palette-focus>Refund</button>
</div>
</form>
List the modes
curl -b cookies.txt https://acme.com/admin/palette/modes
[
{ "code": "backend.do", "label": "Do", "placeholder": "What do you want to do?",
"prefix": ">", "url": "/admin/palette/do", "live": true },
{ "code": "acme.lookup", "label": "Look up", "placeholder": "An order number",
"prefix": "#", "url": "/admin/acme/lookup/ask", "live": true }
]
The Do mode
backend.do (prefix >) lists the abilities a person may
run and walks one through its input, its preview and its result.
| Ability | In Do |
|---|---|
Input of strings, numbers, booleans and enum choices | offered, one control per property |
| Input with an object or an array | left out |
Effect::Read | runs when chosen |
| Any other effect | shows its Preview, then runs on confirmation |
Effect::Delete, Effect::Send | the confirmation is a danger button |
backend.records.* | left out |
A property’s title is its label and its doc comment the help under it.
A name or a choice with no title reads as words: found_on_site shows as
“Found on site”.
Admin Screens
A module mounts a screen inside the admin for what a list and a form cannot express: an import wizard, a report, a diff view.
Take axum from the framework
use laterite_admin::axum::{routing::get, Router};
use laterite_core::strata::async_trait;
Never add axum or async-trait to a plugin’s Cargo.toml.
Mount an admin screen
use laterite_admin::routes::{RouteCtx, Screen, ScreenReg};
struct Importer;
impl Screen for Importer {
fn mount(&self, ctx: &RouteCtx) -> Router {
let db = ctx.db().clone();
Router::new()
.route("/", get(upload_form).post(run_import))
.route("/report", get(move || show_report(db.clone())))
}
}
fn register(&self, registry: &mut Registry) {
registry.add_screen(
ScreenReg::new("/import", "acme.import", Arc::new(Importer))
.in_menu(t!("Import places")),
);
}
ScreenReg | Description |
|---|---|
new(path, permission, screen) | path sits under the module’s identity: acme.places at /import serves /admin/acme/places/import. permission is required and enforced before the handler runs. |
.in_menu(label) | Adds it to the main menu. Without it the screen still mounts, reached by link. |
The screen runs behind the session, CSRF protection and the error pages.
Render a page in the admin
use askama::Template;
use laterite_admin::axum::{Extension, Router};
use laterite_admin::html::Markup;
use laterite_admin::{AdminError, Shell};
use laterite_core::t;
#[derive(Template)]
#[template(path = "places.html")]
struct PlacesTemplate<'a> {
shell: &'a Shell,
rows: Vec<String>,
}
async fn places(Extension(shell): Extension<Shell>) -> Response {
let body = PlacesTemplate { shell: &shell, rows: vec![] };
match Markup::from_template(&body) {
Ok(body) => shell.page(&t!("Places"), body),
Err(e) => AdminError::Internal(e.into()).into_response(),
}
}
<div class="lat-card">
<form method="post" action="/admin/places">
<input type="hidden" name="_csrf" value="{{ shell.csrf_token() }}">
<button class="lat-btn lat-btn--primary" type="submit">{{ shell.t("Save") }}</button>
</form>
</div>
| Method | Does |
|---|---|
shell.page(&title, body) | The body inside the chrome: nav, flash messages, assets, the title as the heading. |
shell.t("Save"), shell.tt(&text) | A string, or a Text, in the user’s locale. |
shell.csrf_token() | The request token for a form the template builds. First in an upload form. |
shell.datetime(&utc) | An RFC 3339 timestamp in the user’s timezone. |
shell.base() | The admin mount, for a link into the panel. |
The admin’s stylesheet is already on the page: lat-card, lat-table,
lat-fields, lat-field, lat-input, lat-select, lat-check, lat-facts,
lat-actions, lat-btn, lat-alert, lat-help, lat-status. A
SessionHandle extension carries push_flash; an AdminError renders the
styled 404, 403 or 500. Headings, dialogs, split panes and chrome builders are
on Page Layout.
Choose where it mounts
fn admin_base(&self) -> Option<&'static str> { Some("/places") }
[backend.paths]
"acme.places" = "/geography"
"acme.places/import" = "/geography/bulk-upload"
The deployment has the last word. Two modules on one path, or one on a framework screen, abort the boot naming both.
Link to yourself
ctx.url("/report") // "/admin/places/import/report", wherever it mounted
ctx.base_url() // the site origin, from app.url or the bind address
base_url is for a URL a route emits: a sitemap <loc>, a canonical, a feed
entry. Never build one from the Host header.
Add middleware
fn mount(&self, _ctx: &RouteCtx) -> Router {
Router::new()
.route("/", get(robots_txt))
.layer(CompressionLayer::new())
}
Read other modules’ contributions
pub struct FeedReg {
pub name: String,
}
impl PublicRoute for Feeds {
fn mount(&self, ctx: &RouteCtx) -> Router {
let feeds: Vec<&FeedReg> = ctx.contributions::<FeedReg>();
// ...
}
}
Any Send + Sync type another module registers. Contributions the framework
consumes itself (resources, screens, settings, permissions, persisters,
listeners, column types, public routes) are not visible here.
Write through a resource’s form
use std::collections::HashMap;
use laterite_admin::persist::SaveError;
use laterite_core::Actor;
impl Screen for Importer {
fn mount(&self, ctx: &RouteCtx) -> Router {
let products = ctx.form("/products").expect("the products resource");
Router::new().route("/run", post(move || {
let products = products.clone();
async move {
let actor = Actor::system("acme.import");
let mut row = HashMap::new();
row.insert("sku".to_string(), "A-100".to_string());
row.insert("name".to_string(), "Anvil".to_string());
match products.create(row, &actor).await {
Ok(id) => format!("created {id}"),
Err(SaveError::Invalid(bag)) => format!("refused: {bag:?}"),
Err(SaveError::Failed(e)) => format!("failed: {e}"),
}
}
}))
}
}
ctx.form(path) takes the resource’s path as its descriptor declares it, relative
to the admin root, and is None when nothing with a form mounts there.
| Method | Does |
|---|---|
create(data, &actor) | Validates data as a submission, saves a new record through the form’s field types, listeners and persister, and returns its id. |
update(id, data, &actor) | The same as an edit of the record id. Every field is written; one left out of data is written blank. |
entity(), id_field() | The table and its primary key column. |
fields() | The declared fields, in order; data is keyed by their names. |
SaveError::Invalid carries the per-field messages a refused submit shows;
SaveError::Failed is the write failing. The audit log records the actor.
Public Routes
A module mounts an endpoint outside the admin: a feed, a robots.txt, a
webhook. No session, no permission, no admin chrome.
Mount a public route
use laterite_admin::axum::{routing::get, Router};
use laterite_admin::routes::{PublicRoute, PublicRouteReg, RouteCtx};
struct Robots;
impl PublicRoute for Robots {
fn mount(&self, _ctx: &RouteCtx) -> Router {
Router::new().route("/", get(robots_txt))
}
}
registry.add_public_route(PublicRouteReg::new("/robots.txt", Arc::new(Robots)));
PublicRouteReg | Description |
|---|---|
new(path, route) | path is literal, never namespaced. A route inside the admin mount is refused. |
A POST must come from the site’s own origin. A route that authenticates each request itself (an API token, a signed webhook) leaves that check:
registry.add_public_route(
PublicRouteReg::new("/api/capture", Arc::new(Capture)).skip_origin_check(),
);
PublicRouteReg | Description |
|---|---|
skip_origin_check() | The path and everything below it skip the origin check. The route verifies each request. |
A path can also be listed in backend.origin_check_except. See Admin. ctx.url, ctx.base_url, middleware and
other modules’ contributions work as on an
admin screen.
Page Layout
The heading, side panel, dialogs, split panes and chrome builders a contributed screen composes its page from.
Head a page
use laterite_admin::PageHead;
let actions = Markup::from_template(&ActionsTemplate { shell: &shell })?;
shell.page_with(
PageHead::new(t!("Places")).back(t!("Regions"), ctx.url("")).actions(actions),
body,
)
<a class="lat-btn lat-btn--secondary lat-btn--sm" href="{{ export_href }}">{{ shell.t("Export") }}</a>
<details class="lat-menu">
<summary class="lat-btn lat-btn--secondary lat-btn--sm">{{ shell.t("Manage") }} ▾</summary>
<div class="lat-menu__panel">
<button type="button" data-lat-dialog="new-place">{{ shell.t("New place") }}</button>
<div class="lat-menu__divider"></div>
<form method="post" action="{{ purge_href }}"><input type="hidden" name="_csrf" value="{{ shell.csrf_token() }}"><button class="is-danger" type="submit" data-lat-confirm='{{ shell.t("Purge every place?") }}'>{{ shell.t("Purge") }}</button></form>
</div>
</details>
| Method | Does |
|---|---|
PageHead::new(title) | The heading. |
.back(label, href) | A link above the heading to the page this one sits under. |
.actions(markup) | Controls in the band under the heading: buttons, a details.lat-menu, dialog openers. |
.aside(label, markup) | A context side panel beside the body, folded under label on a narrow window. |
.assets(assets) | Scripts and styles the page needs, such as CODE_EDITOR_ASSETS. |
shell.page_with(head, body) | The body under that head, inside the chrome. |
Add a side panel
let panel = Markup::from_template(&RegionsTemplate { shell: &shell, regions })?;
shell.page_with(
PageHead::new(t!("Places")).aside(t!("Regions"), panel),
body,
)
<nav class="lat-pane" aria-label='{{ shell.t("Regions") }}'>
<ul class="lat-nav">
{% for r in regions %}<li><a class="lat-nav__item{% if r.active %} is-active{% endif %}" href="{{ r.href }}">{{ r.name }}</a></li>{% endfor %}
</ul>
</nav>
Open a form in a dialog
<button type="button" class="lat-btn lat-btn--primary lat-btn--sm" data-lat-dialog="new-place">{{ shell.t("New place") }}</button>
<button type="button" class="lat-btn lat-btn--ghost lat-btn--sm" data-lat-dialog="new-place" data-lat-dialog-set="kind=city">{{ shell.t("New city") }}</button>
<dialog class="lat-dialog" id="new-place">
<form method="post" action="{{ base }}">
<div class="lat-dialog__head"><h2>{{ shell.t("New place") }}</h2><button type="button" class="lat-dialog__close" data-lat-dialog-close aria-label='{{ shell.t("Close") }}'>×</button></div>
<div class="lat-dialog__body">
<input type="hidden" name="_csrf" value="{{ shell.csrf_token() }}">
<div class="lat-field">
<label class="lat-field__label" for="kind">{{ shell.t("Kind") }}</label>
<select class="lat-input lat-select" id="kind" name="kind"><option value="city">{{ shell.t("City") }}</option></select>
</div>
<div class="lat-field">
<label class="lat-field__label" for="name">{{ shell.t("Name") }}</label>
<input class="lat-input" id="name" name="name" required autofocus>
</div>
</div>
<div class="lat-dialog__actions"><button class="lat-btn lat-btn--ghost" type="button" data-lat-dialog-close>{{ shell.t("Cancel") }}</button><button class="lat-btn lat-btn--primary" type="submit">{{ shell.t("Create") }}</button></div>
</form>
</dialog>
| Attribute | On | Does |
|---|---|---|
data-lat-dialog="id" | Any control | Opens the dialog.lat-dialog with that id and focuses its first field. |
data-lat-dialog-set="field=value;other=value" | The opener | Fills the named fields before opening. |
data-lat-dialog-close | A control inside | Closes the dialog. Escape and a click on the backdrop close it too. |
.lat-dialog--wide | The dialog | A wider dialog. |
Split a screen
<div class="lat-split">
<nav class="lat-pane">
<div class="lat-pane__head">{{ shell.t("Regions") }}<button type="button" class="lat-btn lat-btn--ghost lat-btn--sm lat-btn--icon" data-lat-dialog="new-region">{{ shell.icon("plus")|safe }}</button></div>
<ul class="lat-nav">
<li><a class="lat-nav__item is-active" href="{{ href }}"><span class="lat-nav__label">{{ shell.t("North") }}</span><span class="lat-nav__meta">12</span></a></li>
</ul>
</nav>
<div class="lat-pane">
<div class="lat-pane__bar"><nav class="lat-breadcrumb"><a href="{{ base }}">{{ shell.t("All") }}</a></nav><form method="get" action="{{ base }}"><input class="lat-input lat-listbar__search" type="search" name="q"></form></div>
<div class="lat-pane__body">{{ content|safe }}</div>
<div class="lat-pane__foot"><button class="lat-btn lat-btn--primary" type="submit">{{ shell.t("Save") }}</button></div>
</div>
</div>
| Class | Renders |
|---|---|
lat-split | A pane beside the content inside a body; lat-split--aside puts the pane after the content. One column on a narrow window. For a panel beside the whole page, PageHead::aside above. |
lat-pane | A framed block; lat-pane__head, lat-pane__bar, lat-pane__body, lat-pane__foot stack inside it. |
lat-nav, lat-nav__item, .is-active | A list of links in a pane, with lat-nav__label and lat-nav__meta. |
shell.icon(name) | An icon from the framework’s set, inline. |
Compose chrome
use laterite_admin::ui::{Badge, Button, Card, Toolbar};
let body = Toolbar::new("Reports")
.button(Button::link("New report", format!("{}/reports/new", ctx.admin_path())).primary())
.button(Button::post("Rebuild", format!("{}/reports/rebuild", ctx.admin_path())).confirm("Rebuild every report?"))
.render(&shell);
let card = Card::new(Markup::from_override(table_html)).render();
let state = Badge::new("Stale").render(&shell);
| Element | Builders | Renders |
|---|---|---|
Button::link(label, href) | .primary(), .danger(), .ghost(), .small(), .icon(name) | A link styled as a button. |
Button::post(label, action) | The same, and .confirm(question) | A form that posts with the request token, asking first when confirm is set. |
Toolbar::new(title), Toolbar::section(title) | .button(..) | A page or section heading, its buttons in the band under it. |
Badge::new(label) | A small label. | |
Card::new(markup) | The panel’s framed block around what it is given. |
Put a checklist on a screen
use laterite_admin::checklist::{Checklist, Choice, Expand, Offer};
use laterite_core::Translator;
let list = Checklist::new("Channels")
.choice(Choice::new("channel", "email", "Email").checked(true))
.group("Chat", vec![
Choice::new("channel", "slack", "Slack").note("One workspace").into(),
Choice::new("channel", "teams", "Teams").locked(true).into(),
])
.select_all(Offer::Auto)
.search(Offer::Never)
.expand(Expand::All);
// `Markup`, for a template's `|safe` slot
let html = list.render(&Translator::new("en"));
| Builder | Does |
|---|---|
Choice::new(name, value, label) | One box, submitted as name=value. |
.note(..), .code(..) | A second line under the label; an identifier beside it. |
.checked(..), .locked(..) | Ticked; shown and not changeable. |
.group(label, entries) | A heading over entries of its own, nested to any depth. |
.select_all(..), .search(..), .expand(..) | The defaults listed under Behaviours. |
.read_only(true) | Every box locked. |
.view(&translator) | The resolved list as a serialisable value, for a field type’s view-model. |
JavaScript API
The window.lat helpers a contributed screen or widget calls, the events every
island announces, and the attributes that join a form of your own in.
Raise a message from script
window.lat.flash('Import finished.', 'success'); // or 'error', which stays until dismissed
Confirm before acting
<button type="submit" data-lat-confirm="Delete the selected records? This cannot be undone.">
Delete
</button>
Ask from script
lat.confirm('Archive 12 articles?', { go: 'Archive', cancel: 'Keep', focus: 'cancel' }, function (yes) {
if (yes) archive();
});
| Label | Does |
|---|---|
go | Names the confirming button. Default OK. |
cancel | Names the other. Default Cancel, localized. |
focus | 'cancel' opens with the cursor on it. Default: the confirming button. |
Join a form in
<form method="post" action="/admin/acme/import" data-lat-widget="form" data-lat-focus="first">
| Attribute | Does |
|---|---|
data-lat-widget="form" | Asks before leaving with changes unsaved. |
data-lat-refused | The form holds a submission that was not saved: it opens changed, with the cursor in the first field carrying an error. |
data-lat-focus | first opens with the cursor in the first field; off leaves it alone. |
data-lat-confirm-leave="off" | Never asks. |
data-lat-counter | On a control with maxlength: auto or on. |
data-lat-grow="off" | On a textarea: keeps the height it was given. |
data-lat-preset, data-lat-preset-type | On a field’s wrapper: the field followed and the shape (slug, url, file, exact). |
data-lat-trigger-action, data-lat-trigger-field, data-lat-trigger-condition | On a field’s wrapper: the dependency, as Field Dependencies spells it. |
Keep Enter inside a widget
<div data-lat-widget="acme-lookup" data-lat-enter-scope data-lat-enter-target=".acme-lookup__go">
<input type="search" name="q">
<button type="button" class="acme-lookup__go">Look up</button>
</div>
| Attribute | Does |
|---|---|
data-lat-enter-scope | On the root of a widget holding an input: Enter acts there and never submits the form around it. |
data-lat-enter-target="<selector>" | The button Enter presses inside that scope. Without a target, Enter does nothing. |
Listen and drive
Every island announces what it does as a DOM event named
lat:<component>:<event>, bubbling from its root. Server-side facts are on the
event bus.
var stop = lat.on('repeater:added', function (detail, event) {
console.log(detail.count, 'rows; the new one is', detail.row);
});
// A `before-` event is cancelable: this caps a repeater at five rows.
lat.on('repeater:before-add', function (detail, event) {
if (detail.count >= 5) event.preventDefault();
});
// Drive an island through its controller.
lat.get(document.querySelector('[data-lat-widget="repeater"]')).add();
// A rich editor: the same three, plus the engine for anything else.
var rich = lat.get(document.querySelector('[data-lat-widget="richeditor"]'));
rich.editor.commands.insertContent('<p>Hello</p>');
// A markdown editor: the same, plus the Preview tab.
lat.get(document.querySelector('[data-lat-widget="markdown"]')).preview();
// A code editor: read, replace, focus.
var code = lat.get(document.querySelector('[data-lat-widget="codeeditor"]'));
code.set(code.get().trim());
code.focus();
| Event | Detail | Cancelable |
|---|---|---|
repeater:before-add | count | Yes |
repeater:added | row, index, count | No |
repeater:before-remove | row, index, count | Yes |
repeater:removed | index, count | No |
repeater:moved | row, from, to, count | No |
repeater:duplicated | row, index, count | No |
ref-picker:changed | id, label, previous | No |
ref-picker:cleared | previous | No |
selection:changed | ids, count | No |
checklist:changed | values, count, total | No |
flash:shown | text, level | No |
flash:dismissed | text | No |
confirm:opened | text | No |
confirm:confirmed, confirm:cancelled | None | No |
copy:copied | value | No |
reveal:shown, reveal:hidden | None | No |
preset:filled | from, value | No |
trigger:changed | field, met | No |
| Controller | Methods |
|---|---|
| Repeater | add(), remove(index), move(from, to), duplicate(index), count() |
| Record picker, searched select | value(), label(), choose({ id, label }), clear() |
| Checklist | values(), count(), set(values), all(), none(), search(text) |
| Form | changed(), settle(): takes the form as it stands for saved |
| Password reveal | show(), hide() |
| Helper | Does |
|---|---|
lat.on(name, handler) | Listens page-wide, swapped content included. Returns the function that stops listening. |
lat.emit(el, name, detail, cancelable) | Announces lat:<name> from el. Returns false when a listener cancelled it. |
lat.get(el) | The controller of the island at or around el. |
lat.scan(root) | Starts the islands in markup a script added. Swapped content starts without it. |
lat.confirm(text, labels, done) | Asks in the admin’s dialog. done hears true or false. |
lat.flash(text, level) | Raises a message: success, or error, which stays until dismissed. |
lat.assets.ensure(url) | Loads a stylesheet or script once. |
Put a code editor on a contributed screen
<div data-lat-widget="codeeditor" data-language="yaml" style="--rows:16">
<textarea class="lat-input lat-editor" id="spec" name="spec" rows="16" data-lat-grow="off">{{ spec }}</textarea>
</div>
shell.page_with(PageHead::new("Specification").assets(laterite_admin::CODE_EDITOR_ASSETS), body)
| Attribute | Values | Default |
|---|---|---|
data-language | text, html, css, javascript, json, yaml, markdown, jinja | text |
data-line-numbers | off | on |
data-wrap | on | off |
--rows | lines | 12 |
readonly on the textarea | A read-only editor |
Without the script the textarea is the control.
Choose from the library
var picker = lat.mediaPicker({
multiple: false,
words: { title: 'Choose from the library', use: 'Use selected', cancel: 'Cancel' },
onDone: function (items) { console.log(items[0].id, items[0].url); }
});
picker.open('/admin/media/pick?mode=image');
| Option | Values |
|---|---|
multiple | true, false |
words | title, use, cancel |
onDone(items) | each item: id, name, kind, thumb, url, is_image |
open(url) | the picker fragment, with ?mode=image for images alone |
Write an island
window.lat.widget('char-count', function (el) {
var input = el.querySelector('input');
function count() { return input.value.length; }
input.addEventListener('input', function () {
el.querySelector('.count').textContent = count();
lat.emit(el, 'acme.char-count:changed', { count: count() });
});
// Returned: `lat.get(el).count()` reads it from outside.
return { count: count };
});
<div data-lat-widget="char-count">
<input type="text" name="title">
<span class="count">0</span>
</div>
| Return | Does |
|---|---|
| The controller object | What lat.get(el) hands out. |
root | The markup an island built around its element; lat.get then finds the controller from inside it too. |
Bind by structure, not by id: the same markup may appear more than once on a page and inside swapped content.
Testing
How a test drives a contributed route without a running server.
Test a route
let ctx = RouteCtx::builder(db)
.admin_path("/backoffice")
.base_url("https://acme.example")
.build();
let response = Robots.mount(&ctx)
.oneshot(Request::get("/").body(Body::empty())?)
.await?;
| Builder | Default |
|---|---|
base_path(..) | /, where the screen mounted. |
admin_path(..) | /admin, where the panel mounted. |
base_url(..) | http://localhost, the site’s origin. |
contributions(registry) | Empty: what ctx.contributions reads. |
events(events) | A bus nothing listens on. |
auth(service) | A default service over the same database. |
Every builder field has a default; name only what you assert on.
Migrations
A migration is a unit with a stable name, an up and an optional down; a
module lists its migrations in apply order.
Write a migration
use laterite_core::strata::*;
One import brings the Migration trait, async_trait, the schema and query
builders, Db, and the column helpers. lat make:migration <description>
writes a new file with it.
One migration per file under src/migrations/, named
m<NNNN>_<description>.rs, declaring pub struct Migration with a stable
name, an up and an optional down. mod.rs lists them in apply order:
laterite_core::migration_set! {
module_id: "acme.blog",
m0001_create_posts,
m0002_create_comments,
}
Append at the end. Never reorder or rename a shipped entry: applied migrations
are tracked by (module_id, name).
Use the column helpers
use laterite_core::{bool_col, key_col};
Table::create()
.table(Article::Table)
.col(key_col(Article::Slug).not_null().unique_key())
.col(bool_col(Article::Published).not_null().default(0));
| Helper | Description |
|---|---|
key_col(name) | A key column: any id, code, token or column named in an index or foreign key. Chain .not_null(), .primary_key(), .unique_key() as usual. Use .text() only for unindexed prose. |
bool_col(name) | A boolean column. Bind and read it as a bool through the query helpers. Chain .not_null(), .default(0) as usual. |
Ids are bigint auto-increment; an insert never sets one. Keep a migration to
one schema change.
Queries
A query is built with the query builder and bound onto the pool through the portable helpers; the same code runs on Postgres, MySQL and SQLite.
Write a query
use laterite_core::strata::*;
let stmt = Query::select()
.column(Article::Title)
.from(Article::Table)
.and_where(Expr::col(Article::Published).eq(true))
.to_owned();
let (sql, values) = build(db.backend, &stmt);
let rows = bind_values(sqlx::query(&sql), values).fetch_all(&db.pool).await?;
Never hand-write SQL with ? placeholders. db is a laterite_core::Db: the
pool paired with its backend.
| Helper | Description |
|---|---|
build(backend, &stmt) | Renders a statement to (sql, values) for the backend. |
bind_values(query, values) | Binds the values onto a query, in order. A bool binds as a bool. |
bind_values_as(query_as, values) | The same, for a query_as mapping rows into a type. |
insert_returning_id(db, stmt, id_column) | Runs an insert and returns the new auto-increment id. |
insert_returning_id_on(backend, conn, stmt, id_column) | The same, on a connection inside a transaction. |
on_conflict_ignore(keys) | An insert’s conflict clause that ignores a duplicate of keys. |
text_cast(backend) | The type name to cast a column to a string: Expr::col(c).cast_as(Alias::new(text_cast(db.backend))). |
Insert a row
let stmt = Query::insert()
.into_table(Article::Table)
.columns([Article::Title, Article::Published])
.values_panic(["Hello".into(), true.into()])
.to_owned();
let id = insert_returning_id(&db, stmt, Article::Id).await?;
Read a row
use laterite_core::AnyRowExt;
let published: bool = row.get_bool("published")?;
let title: String = row.get_text("title")?;
let summary: Option<String> = row.get_text_opt("summary")?;
let views: i64 = row.get_int("views")?;
AnyRowExt | Description |
|---|---|
get_bool(column) | A boolean. |
get_text(column), get_text_opt(column) | A string, or a nullable one. Never try_get::<String>. |
get_int(column), get_int_opt(column) | An integer of any declared width as i64, or a nullable one. |
Models
A model is a struct over one table. #[derive(Model)] reads and writes it
through laterite_core::model.
Generate one
lat make:model article --field title:text,views:integer,published_at:datetime
// src/models/article.rs
use laterite_core::model::{DateTime, Utc};
#[derive(Debug, Clone, laterite_core::Model)]
#[model(table = "articles")]
pub struct Article {
pub id: i64,
pub title: String,
pub views: i64,
pub published_at: Option<DateTime<Utc>>,
}
Declare one
| Attribute | On | Does |
|---|---|---|
#[model(table = "articles")] | The struct | The table; required |
#[model(id = "article_id")] | The struct | The id field; default id, an i64 |
#[model(column = "published_at")] | A field | The column; default the field’s name |
| Field type | Column |
|---|---|
String | Text; null reads as empty |
i64, i32 | Integer |
bool | bool_col |
f64 | Floating point |
DateTime<Utc> | UTC text |
serde_json::Value | JSON as text |
Option<T> | Any of the above, nullable |
Read and write
use laterite_core::model;
let id = model::insert(&db, &Article { id: 0, title: "Hello".into(), views: 0, published_at: None }).await?;
let mut article = model::find::<Article>(&db, id).await?.expect("just inserted");
article.views += 1;
model::update(&db, &article).await?;
let every = model::all::<Article>(&db).await?;
| Function | Returns |
|---|---|
find::<M>(db, id) | Option<M> |
all::<M>(db) | Every row, in id order |
find_many::<M>(db, &ids) | HashMap<i64, M>, one query |
insert(db, &model) | The new id; the model’s own id is ignored |
update(db, &model) | Writes every column to the row with the model’s id |
Load relations for a page
let ids: Vec<i64> = articles.iter().map(Model::id).collect();
let comments = model::has_many::<Comment>(&db, "article_id", &ids, |c| c.article_id).await?;
let authors = model::find_many::<Author>(&db, &author_ids).await?;
Each call is one query for the whole page: has_many groups the rows by their
parent id, find_many keys them by id.
Seeding
A seeder puts a module’s data in the database: reference rows, defaults, demo content. It runs when asked, as often as asked.
Write a seeder
use laterite_core::seed::{insert_missing, Seeder, SeederSet};
use laterite_core::{CoreResult, Db, Record};
struct Statuses;
#[laterite_core::strata::async_trait]
impl Seeder for Statuses {
fn name(&self) -> &str {
"statuses"
}
async fn run(&self, db: &Db) -> CoreResult<()> {
for (code, label) in [("draft", "Draft"), ("live", "Live")] {
let mut rec = Record::new("acme_statuses");
rec.set("code", code).set("label", label);
insert_missing(db, &rec, &["code"]).await?;
}
Ok(())
}
}
insert_missing(db, &rec, &key) inserts the row only when no row holds the
same values in every key column, and returns whether it inserted. A second
run changes nothing.
Register it
impl Module for BlogModule {
fn seeders(&self) -> SeederSet {
SeederSet::new("acme.blog", vec![Box::new(Statuses)])
}
}
Run seeders
lat seed
lat seed acme.blog
| Command | Runs |
|---|---|
lat seed | Every loaded module’s seeders, in load order |
lat seed <module> | One module’s seeders |
cargo run -- seed [module] | The same, from the application binary |
Each seeder that ran prints Seeded <module>/<name>.
Model Listeners
A listener runs when a record is written: fill a column, refuse a save, react to a change. It reaches every entity written through the save pipeline.
Build a record
let mut rec = Record::new("articles");
rec.set("title", "Hello")
.set("views", 0i64)
.set("published", true)
.set("published_at", Utc::now());
rec.text("title"); // Some("Hello")
rec.int("views"); // Some(0)
rec.deserialize::<Article>()?; // a struct view; extra attributes ignored
An absent attribute is not part of the write; a null one writes NULL.
Write a listener
use laterite_core::{ErrorBag, ModelListener, Op, Record, SaveCx, t};
struct Slugify;
#[laterite_core::strata::async_trait]
impl ModelListener for Slugify {
async fn before_save(
&self,
cx: &mut SaveCx<'_>,
rec: &mut Record,
op: Op,
) -> Result<(), ErrorBag> {
let Some(title) = rec.text("title") else {
return Ok(());
};
if title.is_empty() {
let mut bag = ErrorBag::default();
bag.add("title", t!("A title is required."));
return Err(bag);
}
rec.set("slug", slugify(title));
Ok(())
}
}
| Hook | Runs | Return |
|---|---|---|
before_save | Inside the transaction | Err(ErrorBag) refuses and rolls back; the user sees the messages on their fields. |
after_save | After commit | Side effects. Cannot roll back. |
before_delete | Inside the transaction | Err(Text) refuses and rolls back. |
after_delete | After commit | Side effects. |
All optional.
Register it
fn register(&self, registry: &mut Registry) {
registry.add(ModelListenerReg::for_entity("articles", Arc::new(Slugify)));
registry.add(ModelListenerReg::all(Arc::new(AuditWriter)));
}
| Registration | Targets |
|---|---|
ModelListenerReg::for_entity(entity, listener) | Records of one entity. |
ModelListenerReg::all(listener) | Every entity. Must not assume a column exists. |
Read what changed
if rec.has_original() && rec.changed("title") {
let was = rec.original("title").and_then(AttrValue::as_str);
}
changed is false without a snapshot; check has_original first.
Read the actor
match cx.actor() {
Actor::User { id, username } => rec.set("updated_by", *id),
Actor::System { process } => { /* a seeder, a job, the CLI */ }
_ => {}
}
Stamp timestamps
FormConfig { timestamps: true, .. }
form:
timestamps: true
Sets created_at on create and updated_at on every write; a created_at
already on the record is kept. Opt in per form: a column added to every entity
reaches tables without it.
Record who changed a row
form:
footprints: true
FormConfig::new("posts", t!("Post"), "/admin/posts", "id", fields).footprints()
| Column | Set on | Value |
|---|---|---|
created_user_id | Create | The signed-in user’s id; null for a system write |
updated_user_id | Every write | The signed-in user’s id; null for a system write |
A value already on the record is kept.
Generate a slug
form:
slugs:
slug: title
handle: [first_name, last_name]
form.slug("slug", &["title"])
| Case | Result |
|---|---|
| The slug is empty | Built from the sources: Hello World becomes hello-world, then hello-world-2, hello-world-3 |
| The slug was typed and is free | Stored slugged: Hello There becomes hello-there |
| The slug was typed and another row holds it | Refused on the slug field |
| An edit keeps the stored slug | Stored unchanged |
A slug is at most 180 characters, suffix included. Trashed rows hold their slug.
Seal a column
form:
encrypt: [api_key]
form.encrypt(&["api_key"]);
let plain = rec.opened(&crypt, "api_key");
| Value written | Result |
|---|---|
| Plaintext, through the form or an import | Sealed under the application key |
| Null or empty | Kept |
Already sealed, such as from a sensitive field | Kept |
Record::opened returns the plaintext, or None when the value does not open.
Guard a delete
#[laterite_core::strata::async_trait]
impl ModelListener for Guard {
async fn before_delete(&self, cx: &mut SaveCx<'_>, rec: &Record) -> Result<(), Text> {
Err(laterite_core::t!("Three records still reference this one."))
}
}
Deletion is not an Op: a save listener never receives deletes. A
persister refuses deletion unless it overrides delete.
Persisters
A persister replaces the generic insert and update for one entity.
Write a persister
#[async_trait]
impl Persister for NodePersister {
async fn create(&self, cx: &mut SaveCx<'_>, rec: &Record) -> Result<i64, SaveError>;
async fn update(&self, cx: &mut SaveCx<'_>, id: &str, rec: &Record) -> Result<(), SaveError>;
async fn load(&self, cx: &mut SaveCx<'_>, id: &str) -> Result<Option<Record>, SaveError>;
async fn delete(&self, cx: &mut SaveCx<'_>, id: &str, rec: &Record) -> Result<(), DeleteError>;
}
| Method | Default |
|---|---|
create | Required. |
update | Required. |
load | None. The pre-write row, for listeners. |
delete | Refuses. |
cx carries the open transaction. Run every statement on it; never open your
own.
Register it
registry.add_persister(PersisterReg::new("acme.tree", Arc::new(NodePersister)));
FormConfig::new("tree_node", "Node", "/nodes", "id", fields)
.persist("acme.tree")
# descriptors/nodes.yaml
form:
persist: acme.tree
Soft Delete
Delete moves a record to the trash. A trashed record leaves every list, form and export until it is restored or deleted permanently.
Add the column
use laterite_core::strata::*;
Table::create()
.table(Alias::new("notes"))
.col(ColumnDef::new(Alias::new("id")).big_integer().not_null().auto_increment().primary_key())
.col(ColumnDef::new(Alias::new("title")).text().not_null())
.col(soft_delete_col())
.to_owned()
soft_delete_col() is a nullable deleted_at column.
Turn it on
entity: notes
path: /notes
title: Notes
permission: acme.manage_notes
soft_delete: true
list:
deletable: true
columns:
title: {}
Resource::new("/notes", t!("Notes"), list).soft_delete()
The list
| View | Buttons | Route |
|---|---|---|
| The list | Delete moves the selection to the trash; Trash opens the trash | POST {path}/delete |
The trash (?trashed=1) | Restore; Delete permanently; Leave the trash | POST {path}/restore, POST {path}/purge |
A trashed record has no edit page. Delete permanently removes only records that are in the trash.
A trash and a restore are saves: model listeners, timestamps, footprints
and the audit log see an update of deleted_at.
Trash related rows with their parent
relations:
comments:
entity: comments
foreign_key: note_id
soft_delete: true
list:
columns:
body: {}
form:
fields:
body: {}
| Event | Related rows |
|---|---|
| The parent is trashed | Each live row takes the parent’s deleted_at value |
| The parent is restored | Rows carrying that same value are restored; a row trashed on its own stays in the trash |
The related table needs soft_delete_col() too. The section’s own Delete
removes a row permanently.
Leave trashed rows out of a picker
TableSource::new("notes", "id", "title").scope(Arc::new(SoftDelete))
A search skips trashed rows; a stored id still shows its label.
Query Hooks
A query hook adds conditions to every admin read of an entity: list rows and their count, the edit form, export and relation sections.
Write a hook
use laterite_core::{QueryHook, ScopeCx};
use sea_query::{Alias, Expr, SelectStatement};
struct Published;
impl QueryHook for Published {
fn name(&self) -> &str {
"acme.published"
}
fn apply(&self, cx: &ScopeCx<'_>, select: &mut SelectStatement) {
select.and_where(Expr::col((Alias::new(cx.entity), Alias::new("published"))).eq(1));
}
}
Register it
Contributions {
query_hooks: vec![
QueryHookReg::for_entity("posts", Arc::new(Published)),
QueryHookReg::all(Arc::new(TenantOnly)),
],
..Default::default()
}
| Constructor | Applies to |
|---|---|
QueryHookReg::for_entity(entity, hook) | One entity |
QueryHookReg::all(hook) | Every entity a screen reads |
A record a hook hides has no edit page.
Apply hooks in your own query
let mut select = Query::select();
select.column(Alias::new("id")).from(Alias::new("posts"));
laterite_core::scope::apply(&hooks, &ScopeCx::new("posts", db.backend), &mut select, &[]);
The last argument lists hook names to leave out, such as SoftDelete::NAME.
Built-in hooks
| Hook | Name | Condition |
|---|---|---|
SoftDelete | soft_delete | deleted_at IS NULL; added by soft_delete |
Records in Files
A resource’s source keeps its records as files: one file per record in a
folder of the project, read into the table when the application starts and
written back on every save.
# descriptors/posts.yaml
entity: posts
path: /posts
title: Posts
permission: acme.blog.manage_posts
source:
kind: git
path: content/posts
format: markdown
key: slug
body: body
slug_from: title
list:
creatable: true
deletable: true
columns:
title: { searchable: true }
form:
title: Post
fields:
slug: {}
title: { rules: [required] }
pinned: { type: switch }
body: { type: textarea, rows: 12 }
| Option | Description |
|---|---|
path | The folder, relative to the project root. Required. |
kind | files writes the file; git also commits it; or the code of a source a module registered. Default files. |
format | yaml, json, or markdown (YAML front matter and a body). Default yaml. |
key | The text field that names the file. Default slug. |
body | With markdown, the field the body under the front matter holds. Optional. |
slug_from | A field the key is derived from when a save leaves it blank. Optional. |
Scaffold it
lat make:resource article --field title:text --source content/articles --format markdown --git
| Flag | Description |
|---|---|
--source <DIR> | The folder; a slug column names each file. |
--format | yaml, json or markdown; markdown adds a body column. Default yaml. |
--git | Commit every save. |
Declare it from Rust
use laterite_admin::Resource;
use laterite_core::source::{Format, Source};
let posts = Resource::new("/posts", "Posts", list)
.form(form)
.permission("acme.blog.manage_posts")
.source(
Source::git("content/posts", Format::Markdown)
.body("body")
.slug_from("title"),
);
| Constructor | Source |
|---|---|
Source::files(path, format) | The folder, written. |
Source::git(path, format) | The folder, written and committed. |
.body(column), .slug_from(column) | The options above. |
Write a file
<!-- content/posts/hello.md -->
---
title: Hello
pinned: true
---
# Hello
The first post.
| Format | File | Holds |
|---|---|---|
yaml | hello.yaml | The form’s fields as a YAML document. |
json | hello.json | The form’s fields as a JSON object. |
markdown | hello.md | The fields as front matter, the body field under it. |
The file’s name is the key field: letters, digits, dots, dashes and
underscores. The fields are written in the form’s order. A switch is true or
false, a number input is a number, a repeater is a list, anything else is
text.
Starting the application reads the folder: a file’s record is created or updated by key, and a record whose file is gone is removed. A file naming a field the form does not have fails the start, naming the file and the field.
Fit the table
Table::create()
.table(Alias::new("posts"))
.col(ColumnDef::new(Alias::new("id")).big_integer().not_null().auto_increment().primary_key())
.col(ColumnDef::new(Alias::new("slug")).text().not_null())
.col(ColumnDef::new(Alias::new("title")).text().not_null())
.col(bool_col(Alias::new("pinned")).null())
.col(ColumnDef::new(Alias::new("body")).text().null())
.to_owned()
| Column | Rule |
|---|---|
The key field | A text column; the form’s unique rule keeps one file per key. |
| A form field | Any column type the field stores. |
| A column the form does not have | Needs a default, or null. |
Commit every save
source:
kind: git
path: content/posts
| Action | Commit |
|---|---|
| Create | Added content/posts/hello.md (ana) |
| Edit | Updated content/posts/hello.md (ana) |
| Rename the key | The old file is removed in the same commit. |
| Delete | Removed content/posts/hello.md (ana) |
The repository is the project root; git is on the path with a user name and
email configured. Push the branch to publish: a host that builds on push
rebuilds the site.
git push origin main
Build a page per record
use laterite_web::theme::build::{PathsReg, TableKeys};
registry.add(PathsReg::new(
"/posts/:slug",
Arc::new(TableKeys::new("posts", "slug")),
));
# pages/post.htm
url: /posts/:slug
components:
post: { component: "acme.posts", slug: "{{ :slug }}" }
| Name | Gives |
|---|---|
PathsReg::new(pattern, paths) | The pattern’s pages: the build renders it once per set of parameters paths answers. |
TableKeys::new(table, column) | One set per value of column, under the parameter of that name; .param(name) renames it. |
Paths | A trait for any other answer: async fn params(&self, db) -> Vec<Params>. |
lat make:resource --source writes a src/site/<entity>.rs with the component and the PathsReg for /<table>/:slug, registered from the module. A pattern no module answers for is skipped by the build.
Register a source
use laterite_core::source::{PullReport, Pushed, RecordSource, RecordSourceReg, SourceCx, SourceError};
pub struct Sheets;
#[async_trait]
impl RecordSource for Sheets {
async fn pull(&self, cx: &SourceCx<'_>) -> Result<PullReport, SourceError> {
let sheet = cx.source.options["sheet"].as_str().unwrap_or_default();
todo!("read {sheet} into {}", cx.entity)
}
async fn push(&self, cx: &SourceCx<'_>, pushed: &Pushed) -> Result<(), SourceError> {
let row = cx.row(pushed.id).await?;
todo!("write {row:?}")
}
async fn remove(&self, cx: &SourceCx<'_>, key: &str) -> Result<(), SourceError> {
todo!("remove {key} from {}", cx.source.path)
}
}
registry.add(RecordSourceReg::new("acme.sheets", Arc::new(Sheets)));
source:
kind: acme.sheets
path: content/guests
sheet: Guests
| Method | Called |
|---|---|
pull | When the application starts. Creates or updates each row by key and removes the rest. |
push | After a save commits, with the row’s id, the operation, and the key before a rename. |
remove | After a delete commits, with the row’s key. |
cx.row(id) gives the row as the key, the columns by shape, and the body; cx.source.options holds the keys beyond the ones above; cx.actor names who is writing.
Portability
Laterite runs on Postgres, MySQL or SQLite, chosen by the connection URL; migrations and queries are written once.
Use portable types
| You write | Helper |
|---|---|
bool | bool_col in schema; binds as bool; read with AnyRowExt::get_bool |
DateTime<Utc> | Convert to and from RFC 3339 text at the query boundary |
| JSON object or array | serde_json to and from text at the boundary; no in-database JSON operators |
| Key, id or code column | key_col; .text() only for unindexed prose |
| Any string read | AnyRowExt::get_text, get_text_opt; never try_get::<String> |
| Any integer read | AnyRowExt::get_int, get_int_opt |
| Unsigned integer | Automatic |
| New row id | query::insert_returning_id |
| Cast to string | Expr::col(c).cast_as(Alias::new(text_cast(db.backend))) |
| Insert, ignoring a duplicate | query::on_conflict_ignore(keys) |
use laterite_core::{bool_col, AnyRowExt};
Table::create()
.table(Article::Table)
.col(bool_col(Article::Published).not_null().default(0));
let published: bool = row.get_bool("published")?;
let title: String = row.get_text("title")?;
Ids are bigint auto-increment; an insert never sets one. Canonicalise a
user-facing unique key, lower-cased and trimmed, on write and on lookup.
Mind the differences the helpers do not hide
| Backend | Rule |
|---|---|
| SQLite | Foreign keys are enforced with PRAGMA foreign_keys = ON, set for you. Do not disable it. |
| MySQL | Use key_col or .text() for every string column. Keep a migration to one schema change. |
| MySQL | A unique key compares case-insensitively. |
Events
An event is a fact a module announces; a listener acts on it. A listener cannot refuse an action, listen by a wildcard name, or be queued.
Listen
use laterite_auth::events::SignedIn;
use laterite_core::{EventCx, EventError, Listener, Registry};
struct WelcomeBack;
#[laterite_core::strata::async_trait]
impl Listener<SignedIn> for WelcomeBack {
async fn handle(&self, cx: &EventCx<'_>, event: &SignedIn) -> Result<(), EventError> {
acme::greetings::record(cx.db(), event.user_id).await?;
Ok(())
}
}
fn register(&self, registry: &mut Registry) {
registry.listen::<SignedIn>(WelcomeBack);
}
| In a listener | Is |
|---|---|
event | The payload, typed. |
cx.db() | The application’s pool. |
cx.events() | The bus, for announcing a fact of the listener’s own. |
Err(..) | Logged with the event and the listening module. The listeners after it still run, and the announcer is not told. |
Announce
use laterite_core::Event;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
#[non_exhaustive]
pub struct Published {
pub article_id: i64,
}
impl Published {
pub fn new(article_id: i64) -> Self {
Self { article_id }
}
}
impl Event for Published {
const NAME: &'static str = "acme.blog.published";
}
impl Screen for Articles {
fn mount(&self, ctx: &RouteCtx) -> Router {
let events = ctx.events().clone();
let list = ctx.url("/");
Router::new().route("/{id}/publish", post(move |Path(id): Path<i64>| {
let (events, list) = (events.clone(), list.clone());
async move {
// ... write and commit, then:
events.emit(&Published::new(id)).await;
Redirect::to(&list)
}
}))
}
}
| Part | Rule |
|---|---|
NAME | The module’s id, then the fact in the past tense: acme.blog.published. Two types under one name stop the start, naming both. |
| Payload | Serde in both directions. #[non_exhaustive] with a constructor. |
| Moment | After the write has committed. |
| Where | The bus |
|---|---|
| A screen or a public route | ctx.events() on RouteCtx |
Routes added with Bootstrap::extend | ctx.events() on BootstrapCtx |
| A listener | cx.events() |
Beside an AuthService | auth.events() |
Listen for a framework event
Types are in laterite_auth::events.
| Name | Type | Fields |
|---|---|---|
auth.signed_in | SignedIn | user_id, username, ip_address, user_agent |
auth.sign_in_failed | SignInFailed | user_id (none for an unknown username), username, ip_address, user_agent |
auth.locked_out | LockedOut | user_id, username, ip_address, user_agent |
auth.signed_out | SignedOut | user_id |
auth.password_changed | PasswordChanged | user_id, changed_by (none for a process); by_owner() |
Record writes are heard through Model Listeners, which can also refuse one.
Test a listener
let events = Events::builder(db.clone())
.listen::<SignedIn>(WelcomeBack)
.build()?;
// A listener, alone.
events.emit(&SignedIn::new(7, "ada", &RequestContext::default())).await;
// The service announcing to it.
let auth = AuthService::new(db.clone(), AuthConfig::default()).with_events(events.clone());
// A route announcing to it.
let ctx = RouteCtx::builder(db).events(events).build();
let response = Articles.mount(&ctx).oneshot(request).await?;
Sessions and CSRF
A session cookie signs an operator in. Alongside the identity it carries a CSRF token, flash messages and a data blob.
Send the CSRF token
Every POST, PUT, PATCH and DELETE on the admin mount carries the
session’s token, in the _csrf field or the X-CSRF-Token header. Descriptor
forms and htmx requests carry it already. A hand-written form includes it:
<form method="post" action="{{ action }}">
{% include "_csrf.html" %}
...
</form>
A scripted request sends the header; a template exposes the token as
shell.csrf_token:
<button type="button" data-acme-publish data-csrf="{{ shell.csrf_token }}">Publish</button>
document.addEventListener('click', function (e) {
var button = e.target.closest('[data-acme-publish]');
if (!button) return;
fetch(button.dataset.action, {
method: 'POST',
credentials: 'same-origin',
headers: { 'X-CSRF-Token': button.dataset.csrf }
});
});
A request without the token renders a 403 “Request blocked” page. Login and
first-run setup have no session and need no token.
Read an upload
use laterite_admin::VerifiedUpload;
async fn import(mut upload: VerifiedUpload) -> Result<Response, AdminError> {
while let Some(field) = upload.next_field().await? {
// ... stream the field ...
}
Ok(Redirect::to("/admin/import").into_response())
}
An upload’s form puts the token in its first field; VerifiedUpload checks
it while reading and offers the remaining fields as Multipart does. Take an
upload with it, never with a bare multipart parser.
Load scripts as assets
Every admin response carries these; a handler that sets one of its own keeps
its value. Inline scripts and handlers are refused: a screen binds its
behaviour from a script file and a data- attribute.
| Header | Value |
|---|---|
Content-Security-Policy | Scripts and fonts from the admin’s own assets; inline styles allowed; images and media also from https: |
X-Content-Type-Options | nosniff |
X-Frame-Options | SAMEORIGIN |
Referrer-Policy | same-origin |
Permissions-Policy | camera=(), microphone=(), geolocation=(), payment=() |
Cross-Origin-Opener-Policy | same-origin |
Strict-Transport-Security | max-age=31536000; includeSubDomains, with secure_cookie = true |
<button type="button" data-acme-refresh>Refresh</button>
document.addEventListener('click', function (e) {
if (e.target.closest('[data-acme-refresh]')) location.reload();
});
Flash a message
use laterite_admin::{FlashLevel, SessionHandle};
use laterite_core::t;
async fn save(Extension(session): Extension<SessionHandle>, /* ... */) -> Response {
// ... persist ...
session.push_flash(FlashLevel::Success, t!("Settings saved."));
Redirect::to("/admin/settings").into_response()
}
| Call | Description |
|---|---|
push_flash(level, text) | Shown on the next full page, across a redirect, then cleared. |
push_flash_sticky(level, text) | Shown until dismissed. |
FlashLevel | Success, Error, Info. |
Change a password
use laterite_core::Actor;
auth.change_password(
user.id,
&new_password,
Some(&session_token),
&Actor::user(user.id, &user.username),
)
.await?;
| Argument | Value |
|---|---|
user_id | The account whose password changes. |
new_password | Refused under password_policy.min_length (default 8). |
keep_token | The session to keep signed in, or None to end all of them. |
actor | Who made the change, recorded on the audit log. Actor::system("lat admin reset-password") for a process. |
AuthService::password_changed_at(user_id) returns when it last changed, or
None if never recorded.
An operator’s own change, from Preferences → Password, goes through:
auth.change_own_password(user.id, ¤t, &new_password, &session_token, &ctx)
.await?;
| Error | Returned when |
|---|---|
AuthError::InvalidCredentials | current does not match. Counts as a failed sign-in. |
AuthError::TooManyAttempts | The account is locked out. |
AuthError::Refused | The new password is under password_policy.min_length. |
A change through this call is also on the access log as password_changed.
A password made for an operator is temporary:
auth.require_password_change(user.id).await?;
Every admin request then redirects to Preferences → Password until the
operator sets their own. lat admin create --generate and
lat admin reset-password --generate mark the account the same way.
Purge expired sessions
Expired sessions and stay-signed-in credentials are removed for you, and on demand:
lat admin purge
let purged = auth.purge_expired().await?;
println!(
"{} sessions, {} credentials, {} access log rows",
purged.sessions, purged.remember_tokens, purged.access_log
);
Access log rows older than access_log_retention_days go in the same sweep.
Sign out
auth.logout_with(&session_token, &ctx).await?;
The sign-out is on the access log as logout, from the address and client in
ctx. auth.logout(&session_token) records it with neither.
Handle an expired session
Every guarded response carries when the session ends, and a page asks for it on demand:
X-Lat-Session-Ends: 1761307200
GET /admin/session
{"ends":1761307200}
POST /admin/session, with the request token, renews the session to its full
idle window and answers the same way.
A request past the deadline is answered by the kind of request it was:
| Request | Answer |
|---|---|
| Page | A redirect to the login page with ?ended=expired. |
| htmx | 401 with HX-Trigger: lat:session-expired; the admin page signs in again in place and retries the request. |
Scripted (X-Requested-With: fetch) | 401. |
A scripted sign-in posts the login form with X-Requested-With: fetch and
gets JSON back:
POST /admin/login
X-Requested-With: fetch
username=ada&password=...
{"ok": true, "csrf": "<the new request token>", "ends": 1761314400}
{"ok": false, "error": "Invalid username or password."}
A script of your own that posts after a re-login reads the token from the
_csrf field of any rendered form, or from the hx-headers attribute on
body; both are updated.
The page’s dialog and warning announce lat:session:expired and
lat:session:renewed on #lat-session.
Read the sign-out notice
A redirect to the login screen carries ?ended=<code> when the session was
ended for a reason the login page can show; an htmx request gets
HX-Redirect with no body, except for expired (see above).
| Code | Shown when |
|---|---|
expired | Inactivity, or the session’s ceiling. |
password_changed | AuthService::change_password ended every other session. |
deactivated | The account was deactivated. |
signed_out_elsewhere | One device, or every other device, was signed out. |
Localization
English strings in code and templates are the catalog keys. A .po file per
language translates them.
Write translatable text
use laterite_core::{t, tn};
let msg = t!("Your changes were saved.");
let greeting = t!("Welcome back, {name}.").arg("name", user.name.clone());
let label = tn!("{n} item", "{n} items", count).arg("n", count);
| Where | Call |
|---|---|
| Rust | t!("..."); tn!("one", "many", n) for plurals. Both build a Text, localized at render. |
| Template | shell.t("..."); shell.tf(...) with numeric placeholders. |
| Descriptor labels | Already Text, localized where they render. |
A placeholder such as {name} appears unchanged in every translation.
Manage catalogs
lang/
messages.pot # generated template, every source string
de.po # a German translation
lat i18n extract # regenerate every messages.pot
lat i18n update de # create or refresh de.po from the template
lat i18n status # per-locale coverage
lat i18n check # fail if any messages.pot is stale; run in CI
A translator fills in msgstr:
#: templates/login.html
msgid "Admin panel"
msgstr "Verwaltung"
Ship a language from a module
impl Module for AcmeModule {
fn catalogs(&self) -> &'static [(&'static str, &'static str)] {
&[
("de", include_str!("../lang/de.po")),
("fr", include_str!("../lang/fr.po")),
]
}
}
A malformed catalog, or one whose placeholders differ from the source, fails the start.
Set the language
| Order | Source |
|---|---|
| 1 | The operator’s preference, from Preferences. |
| 2 | The browser’s Accept-Language. |
| 3 | backend.locale. |
| 4 | English. |
Only a language with a loaded catalog is offered or chosen. Month and day
names follow a locale that carries a territory, de_DE.
Preview coverage
Set the locale to xx, or send Accept-Language: xx: every translated
string renders bracketed and accented, [Ṡäṽé]. Plain text is a string that
bypassed translation.
Search
A SearchProfile sets how a lookup folds a query and widens it before
matching. A list’s search box folds case over its searchable columns and
takes no profile.
Attach a profile to a picker source
use laterite_admin::picker::TableSource;
use laterite_core::search::{Numerals, SearchProfile};
let source = TableSource::new("acme_cities", "id", "name_folded")
.with_search(SearchProfile::folding().with_expander(Numerals));
let profile = SearchProfile::folding();
assert_eq!(profile.fold(" Ávila's Café "), "avilas cafe");
| Constructor or method | Description |
|---|---|
SearchProfile::new() | Folds case only, matched by substring. The default of every lookup. |
SearchProfile::folding() | Folds case, diacritics, punctuation and whitespace. |
with_chain(chain) | A NormalizerChain of your own. |
with_expander(expander) | Adds a way of widening the query; may repeat. |
with_matcher(matcher) | A matcher of your own, used when the database supports it. |
fold(text) | The folded form of text. |
candidates(query) | The folded query and its expansions. |
| Normalizer | Effect |
|---|---|
Lowercase | Case. |
Diacritics | Accents removed. |
Punctuation | Removed. |
Whitespace | Collapsed. |
NormalizerChain::standard() applies all four in order;
NormalizerChain::new().with(..) builds one by hand. A profile folds the
query, not stored values: widen it only where the column holds folded values.
NormalizerChain::fingerprint() names the chain,
case+diacritics+punctuation+whitespace; keep it beside folded data and
compare after a chain change.
Turn on a list’s search box
list:
search: { prompt: Search by title, on_enter: true }
columns:
title: { label: Title, searchable: true }
body: { label: Body, searchable: false }
| Option | Description |
|---|---|
search.enabled | false removes the box. On by default. |
search.prompt | The placeholder. “Search” when unset. |
search.on_enter | Ask on Enter only. Off by default: the list narrows as the operator types. |
<column>.searchable | Whether the box matches this column. Text columns are searchable by default; other types are not. |
Add an alias
use laterite_core::search::{Aliases, SearchProfile};
let profile = SearchProfile::folding()
.with_expander(Aliases::new().pair("bengaluru", "bangalore"));
Aliases::pair(a, b) makes each find the other. Fold alias values through
the same chain before adding them.
Widen matching
use laterite_core::search::{NormalizerChain, Numerals, SearchProfile};
let profile = SearchProfile::new()
.with_chain(NormalizerChain::standard())
.with_expander(Numerals);
| Expander | Effect |
|---|---|
Numerals | English number words and digits, both ways, on whole tokens: 7 rivers finds seven rivers. |
Aliases | Pairs that reach each other. |
An expander widens the query alone; stored data is untouched.
Storage Disks
A disk holds files; a record points at one and your tables point at the record. The media table migrates with the admin; the crate is a dependency only for code that calls it.
[dependencies]
laterite-media = "0.12"
| Term | Meaning |
|---|---|
| Blob | The bytes of a file. |
| Record | A file with a stable id, pointing at a blob. |
| Link | Attaches a record to its owner. |
Replacing a file makes a new blob; the record’s id and every reference to it stay.
Declare disks
let public = LocalDisk::new("storage/media").public_at("/storage/media");
let private = LocalDisk::new("storage/private");
fn register(&self, registry: &mut Registry) {
registry.add(DiskReg::new("private", Arc::new(private)).label("Uploads kept out of the library"));
}
| Disk | Serving |
|---|---|
| Public | Files served directly at the path. |
| Private | No public URL; streamed through the application. |
A module that stores files reads the disks through
ctx.contributions::<DiskReg>() and picks one by name. The admin’s import
keeps uploads on private: the registered disk of that name, else private
under backend.storage. The library uploads to public, else media there.
Add an S3 disk
[dependencies]
laterite-media = { version = "0.12", features = ["s3"] }
use laterite_media::{DiskReg, S3Config, S3Disk};
let config: S3Config = settings.get("storage.disks.s3")?;
let disk = Arc::new(S3Disk::from_config(&config).await);
registry.add(DiskReg::new("s3", disk));
[storage.disks.s3]
bucket = "acme-media"
region = "auto"
endpoint = "https://<account>.r2.cloudflarestorage.com"
access_key = "..."
secret_key = "..."
prefix = "media"
public_url = "https://media.acme.test"
| Key | Default | Meaning |
|---|---|---|
bucket | The bucket. | |
region | auto | The region name. |
endpoint | AWS | The store’s URL (R2, MinIO, B2, Spaces, Wasabi). |
access_key, secret_key | the SDK’s default chain | Static credentials. |
prefix | "" | A key prefix every blob goes under. |
public_url | none | The origin blobs are reachable at unsigned; unset, the disk is private and serves through presigned URLs. |
path_style | true with an endpoint | endpoint/bucket/key addressing. |
signed_url presigns a GET, presigned_put a PUT for a direct
upload, and copy is server-side.
Take a file in
use laterite_media::{ingest, LocalDisk};
let disk = LocalDisk::new("storage/private");
let stored = ingest(&disk, stream, 10 * 1024 * 1024).await?;
let id = laterite_media::record::create(&db, NewMedia {
disk: "private".into(),
hash: stored.hash,
size: stored.size as i64,
content_type: stored.content_type,
original_name: filename,
in_library: false,
created_by: Some(user.id),
}).await?;
ingest(disk, stream, limit) takes any byte stream: a browser upload, a
server-side fetch, a URL import. It aborts and discards past the limit, and
sniffs the content type from the bytes.
Receive an upload
async fn receive(mut upload: VerifiedUpload) -> impl IntoResponse {
while let Some(field) = upload.next_field().await? {
// the token field is already consumed and checked
}
}
<form method="post" action="{{ action }}" enctype="multipart/form-data">
<input type="hidden" name="_csrf" value="{{ shell.csrf_token() }}">
{% let upload_id = "file" %}
{% let upload_accept = ".csv" %}
{% let upload_multiple = false %}
{% let upload_url = String::new() %}
{% let upload_fields = String::new() %}
{% let upload_direct = String::new() %}
{% let upload_hint = shell.t("A CSV file.") %}
{% include "_upload.html" %}
<button class="lat-btn lat-btn--primary" type="submit" data-upload-submit>{{ shell.t("Upload") }}</button>
</form>
_csrf comes first in the form, or arrives as the X-CSRF-Token header. A
route that parses the upload without VerifiedUpload has its response
refused.
| Variable | Value |
|---|---|
upload_id | The input’s id, for its label. |
upload_accept | An accept list, or empty. |
upload_multiple | true for several files. |
upload_url | Empty: the form submits the file. A URL: the zone posts each file there itself, with _csrf first and X-Requested-With: fetch, shows its progress, and reloads once every file is stored. |
upload_fields | Fields sent before each file (folder=3;kind=image). |
upload_direct | Empty, or the URL of a direct upload route the zone tries first. |
upload_hint | A line under the prompt. |
data-upload-submit | On the form’s button: hidden while the zone sends. |
A route the zone posts to answers JSON:
{"stored": [{"id": 7, "name": "cover.png", "href": "/admin/media/7", "url": "/storage/media/<hash>/cover.png"}],
"refused": [{"name": "huge.mov", "reason": "Larger than the upload limit."}]}
| Event | Detail |
|---|---|
lat:upload:picked | {count}, in a form. |
lat:upload:before-send | {count}, cancelable. |
lat:upload:stored, lat:upload:failed | {name, reason} per file. |
lat:upload:done | {failed} once every file answered. |
Check what comes in
# config/default.toml
[backend]
upload_extensions = ["jpg", "jpeg", "png", "webp", "svg", "pdf", "css"]
use laterite_media::sanitize;
if !sanitize::extension_allowed(&name, ctx.upload_extensions()) {
return refused(t!("This file type is not allowed."));
}
let bytes = match sanitize::svg(&bytes) {
Some(drawing) => drawing.into_bytes(),
None if sanitize::is_svg(&bytes) => return refused(t!("The image could not be read.")),
None => bytes,
};
| Function | Does |
|---|---|
extension_allowed(name, list) | The name’s extension, lowercased, is in the list. A name with none is refused. |
is_svg(head) | The leading bytes are an SVG document, past any prolog, comment or doctype. |
svg(bytes) | The SVG as a drawing: script, foreign content, event handlers, external references and javascript: URLs removed; style cleaned; the namespace present. None when it is not an SVG. |
css(text) | A stylesheet without imports, script URLs, expressions, bindings or a closing tag. |
DEFAULT_EXTENSIONS | The list when upload_extensions is empty: images, documents, audio, video, fonts, archives. |
The library’s own upload, direct upload and media field run these checks.
Serve a file
Every record serves at /storage/media/<hash>/<name>:
| Header | Value |
|---|---|
ETag | The hash; If-None-Match answers 304. |
Cache-Control | public, max-age=31536000, immutable |
X-Content-Type-Options | nosniff |
Content-Disposition | inline, or attachment for SVG, HTML, script and any Other kind. |
A record on a disk registered .private() serves only at a signed URL:
registry.add(DiskReg::new("vault", Arc::new(private)).private());
let url = laterite_admin::medialib::file_url(&record);
let timed = laterite_admin::medialib::signed_file_url(&ctx, &record, Duration::from_secs(3600));
// /storage/media/<hash>/<name>?e=<expiry>&t=<signature>
| Part | Value |
|---|---|
e | Expiry, seconds since the epoch. |
t | A signature over the hash and the expiry, made with backend.secret. |
Cache-Control | private, no-store |
| Bare, expired, altered or retargeted | 404 |
Inside the admin a private file has an address of its own, with no signature:
/admin/media-files/<id>/<name>
/admin/media-files/<id>/<preset>/<name>
| Who asks | Answer |
|---|---|
| Signed out | The sign-in page. |
| A superuser | The file. |
Holds media.browse, and the file is in the library | The file. |
| Holds the permission of a resource or relation whose record the file is attached to | The file. |
| Anyone else | 404 |
Write a driver
#[async_trait]
impl StorageDriver for MyDisk {
async fn put(&self, path: &str, data: ByteStream) -> Result<(), StorageError>;
async fn get(&self, path: &str) -> Result<ByteStream, StorageError>;
async fn delete(&self, path: &str) -> Result<(), StorageError>;
async fn metadata(&self, path: &str) -> Result<Option<BlobMeta>, StorageError>;
fn public_url(&self, path: &str) -> Option<String>;
async fn signed_url(&self, path: &str, expires_in: Duration, disposition: Disposition)
-> Result<Option<String>, StorageError>;
}
There is no list(). Write to a temporary path and move into place.
signed_url defaults to None: the framework then streams the file itself
behind its own token. A store that presigns returns the URL.
Encryption and Signing
The application key seals values at rest, signs links and mints tokens with an expiry; every operation names a purpose, and a value sealed for one purpose never opens under another.
lat key generate
# config/local.toml
[app]
key = "1:k8xq...=" # id:<base64 of 32 bytes>; or LAT__APP__KEY
previous_keys = ["0:u9Yr...="] # keys retired by a rotation, still read
let crypt = ctx.crypt();
let sealed = crypt.encrypt("api-secret", b"integrations.token.42", b"hunter2")?;
let plain = crypt.decrypt("api-secret", b"integrations.token.42", &sealed)?;
let signature = crypt.sign("export-link", b"report:7");
let ok = crypt.verify("export-link", b"report:7", &signature);
let token = crypt.token("password-reset", b"user:7", Duration::from_secs(3600));
let payload = crypt.check_token("password-reset", &token)?;
let index = crypt.blind_index("pan", b"1234-5678");
| Method | Does |
|---|---|
encrypt(purpose, aad, plain) | Seals plain, bound to aad; base64url text with the key id inside. |
decrypt(purpose, aad, sealed) | Opens a value sealed under any key the application holds; CryptError::Invalid on a wrong purpose, AAD, key or tampering. |
sign(purpose, message) | A signature of message, base64url. |
verify(purpose, message, signature) | Constant-time check under any held key. |
token(purpose, payload, ttl) | A signed token carrying payload and an expiry. |
check_token(purpose, token) | The payload while the token lives; CryptError::Expired after. |
blind_index(purpose, plain) | A keyed digest to find a sealed value by equality. |
aad names what the value belongs to (a table, column and row); a sealed value moved to another row does not open. ctx.sign and ctx.verify_signature on a route are sign and verify for the url purpose.
Set the key
| Key | Description |
|---|---|
app.key | id:<base64> of 32 random bytes; lat key generate writes one into config/local.toml. Unset, a key derived from backend.secret or the key stored at the first start is used, and a production start logs a warning. |
app.previous_keys | Keys retired by a rotation, each id:<base64>, used for reading only. |
| Command | Does |
|---|---|
lat key generate | Writes a new key as app.key. A key already set is replaced; add --rotate to keep it under previous_keys, or --print to print without writing. |
lat key show | The id of the key in use and of the previous keys. |
Seal a form field
fields:
api_token: { type: sensitive }
The sensitive field stores its value sealed and reveals it on request, recorded in the audit log.
Rotate the key
lat key generate --rotate
lat crypt rotate # re-seals stored values under the new key
lat crypt rotate re-seals every sensitive column under the key in use and reports what it re-sealed, what was already current and what did not open. Remove the old key from previous_keys once it reports nothing left to re-seal. Without an app.key, --rotate keeps the key derived from backend.secret as the previous key.
Test with a key of your own
let crypt = laterite_core::Crypt::ephemeral();
let ctx = RouteCtx::builder(db).build(); // builds on an ephemeral key
Cache
A value is kept under a key for a lifetime, together with the namespaces it was built from. A write bumps its namespace; every value built from that namespace misses from then on, in every process of the deployment.
use std::time::Duration;
use laterite_core::cache::records;
let menu: Vec<MenuItem> = ctx
.cache()
.remember(
"acme.blog::menu",
Duration::from_secs(3600),
&[&records("posts"), "acme.blog::feed"],
|| async { load_menu(ctx.db()).await },
)
.await?;
| Method | Does |
|---|---|
remember(key, ttl, deps, load) | The value under key, or what load returns, stored for ttl as JSON and built from deps. Concurrent callers for one key share one load. |
get(key) | The bytes under key while every namespace in its deps stands where it stood; get_json::<T> decodes them. |
put(key, bytes, deps, ttl) | Stores bytes; put_json(key, &value, deps, ttl) stores a value as JSON. |
add(key, bytes, deps, ttl) | Stores only when nothing is under key; true when it did. |
forget(key) | Drops the value under key. |
bump(namespace) | Moves the namespace on; returns the new generation. |
generation(namespace) | The namespace’s generation. |
lock(name, ttl) | Some(lock) when no other holder has name; see below. |
flush() | Drops every value this process holds. |
A namespace in deps is one registered below, or one of the record family records::<entity>. An unregistered one is refused with CoreError::Validation.
Configure the store
# config/default.toml
[cache]
store = "auto" # auto | null | memory | redis
memory_mib = 64
poll_seconds = 2
# url = "redis://127.0.0.1:6379/0"
# prefix = "acme"
| Key | Description |
|---|---|
cache.store | auto is null while app.debug is on and memory otherwise. Default auto. |
cache.memory_mib | The memory store’s capacity. Default 64. |
cache.poll_seconds | How often a process reads the generations the other processes bumped; 0 turns it off for a single process. Default 2. |
cache.url | The Redis URL for the redis store. |
cache.prefix | The prefix of every Redis key. Default laterite. |
[dependencies]
laterite-core = { version = "0.12", features = ["redis"] }
| Store | Values | Generations and locks |
|---|---|---|
null | Kept nowhere | The database |
memory | This process | The database |
redis | Redis | Redis |
Register a namespace
use laterite_core::cache::CacheNamespace;
fn register(&self, registry: &mut Registry) {
registry.add(CacheNamespace::new("feed"));
}
The namespace is acme.blog::feed: the registering module’s id, two colons, the name.
| Namespace | Bumped by |
|---|---|
records::<entity> | Every save and delete of the entity through the admin or a FormHandle. |
laterite.settings::values | A save through ctx.settings(). |
laterite.parameters::values | A write through ctx.parameters(). |
laterite.theme::templates | A theme write through Themes. |
Write through the handles
ctx.settings().save(&BrandSetting { app_name: "Acme".into(), ..Default::default() }).await?;
ctx.parameters().set("acme.blog::sync.cursor", &cursor).await?;
Themes::of(ctx).save_template(theme.id, Kind::Page, "about.htm", None, markup, None).await?;
ctx.cache().bump("acme.blog::feed").await?;
| Handle | Raw function |
|---|---|
ctx.settings().set / .save | laterite_admin::settings::set / save |
ctx.parameters().set / .reset | laterite_core::parameters::set / reset |
Themes::of(ctx).save_template and the other writes | laterite_web::theme::store::* |
A raw function writes the table alone; the handle writes it and bumps.
Hold a lock
if let Some(lock) = ctx.cache().lock("acme.blog::sync", Duration::from_secs(300)).await? {
sync(ctx.db()).await?;
lock.release().await?;
}
A lock not released lapses when its lifetime passes.
Clear from the command line
lat cache clear # every namespace
lat cache clear --namespace records::posts
lat cache list
Queue
A job is a struct that implements Job; pushing it stores the struct as JSON, and a worker runs it with retries, a timeout and a failed list.
use laterite_core::queue::{Job, JobCx, JobError, QueueRegistry};
use laterite_core::strata::async_trait;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct SendDigest {
user_id: i64,
}
#[async_trait]
impl Job for SendDigest {
const NAME: &'static str = "acme.blog::send_digest";
async fn run(&self, cx: &JobCx) -> Result<(), JobError> {
digest::send(cx.db(), self.user_id).await?;
Ok(())
}
}
fn register(&self, registry: &mut Registry) {
registry.add_job::<SendDigest>();
}
ctx.queue().push(&SendDigest { user_id: 7 }).await?;
ctx.queue().push_in(&SendDigest { user_id: 7 }, Duration::from_secs(600)).await?;
ctx.queue().push_at(&SendDigest { user_id: 7 }, tonight).await?;
| Method | Does |
|---|---|
push(&job) | Stores the job, due now. Pushed::Queued(id), Pushed::Ran in inline mode, Pushed::Duplicate when its unique key is already waiting. |
push_in(&job, delay) | Due after delay. |
push_at(&job, when) | Due at when. |
counts() | How many jobs wait and run on each queue. |
failed() | The failed list, newest first. |
retry(id) / forget(id) | Put a failed job back, or drop it; None for every one. |
clear(queue) | Drops the waiting jobs on one queue, or on all with None. |
A job whose type is not registered is refused at push with CoreError::Validation.
Set the job’s rules
#[async_trait]
impl Job for SendDigest {
const NAME: &'static str = "acme.blog::send_digest";
async fn run(&self, cx: &JobCx) -> Result<(), JobError> { /* ... */ }
fn queue(&self) -> String { "mail".into() }
fn tries(&self) -> u32 { 5 }
fn backoff(&self, attempt: u32) -> Duration { Duration::from_secs(30 * u64::from(attempt)) }
fn timeout(&self) -> Option<Duration> { Some(Duration::from_secs(120)) }
fn retry_until(&self) -> Option<DateTime<Utc>> { Some(Utc::now() + Duration::hours(6)) }
fn unique_key(&self) -> Option<String> { Some(format!("digest:{}", self.user_id)) }
}
| Method | Default | Meaning |
|---|---|---|
queue() | default | The queue the job lands on. |
tries() | 3 | Attempts before the job fails; 0 leaves it to retry_until. |
backoff(attempt) | 10 s, doubling | The wait after attempt attempt failed. |
timeout() | 60 s | The longest one attempt may run; None for no limit. |
retry_until() | None | Keep retrying until this moment, whatever tries says. |
unique_key() | None | A push while a job with this key waits or runs is dropped, scheduled pushes included. |
| Return | Effect |
|---|---|
Ok(()) | The job is removed. |
Err(JobError::retry(message)) | Released for the next attempt after the backoff, or failed on the last one. |
Err(JobError::fail(message)) | Failed at once, whatever tries remain. |
Err(JobError::release(wait, reason)) | Back after wait on the same attempt: a rate limit or a Retry-After. |
async fn run(&self, cx: &JobCx) -> Result<(), JobError> {
let token = cx.crypt().and_then(|c| c.decrypt(FIELD_PURPOSE, b"api_token", &sealed).ok());
match acme::api::fetch(token).await {
Err(acme::api::Error::Limited { retry_after }) => Err(JobError::release(retry_after, "rate limited")),
Err(e) => Err(JobError::retry(e)),
Ok(page) => {
cx.queue().push(&StorePage { page }).await?;
Ok(())
}
}
}
| Method | Returns |
|---|---|
db(), events(), cache(), parameters() | The application’s services. |
queue() | The queue, to push further jobs. |
crypt() | The application’s crypt, None on a queue built without one. |
attempt() | Which attempt this is, from 1. |
queue_name() | The queue the job was taken from. |
id() | The job’s row id, None inline. |
Configure the queue
# config/default.toml
[queue]
store = "auto" # auto | database | redis
mode = "worker" # worker | external | inline
workers = 2
queues = ["default"]
retry_after_seconds = 90
poll_seconds = 1
# url = "redis://127.0.0.1:6379/0"
# prefix = "acme"
| Key | Description |
|---|---|
queue.store | Where jobs wait. auto is database; redis needs the redis feature of laterite-core and queue.url. |
queue.url | The Redis URL for the redis store. |
queue.prefix | The prefix of every Redis key. Default laterite. |
queue.mode | worker runs the workers in the application process; external leaves them to queue work; inline runs a job as it is pushed. |
queue.workers | How many workers the process runs in worker mode. Default 2. |
queue.queues | The queues a worker takes from, in priority order: a job waiting on an earlier queue is taken first. Default ["default"]. |
queue.retry_after_seconds | After this long a claimed job counts as abandoned and is claimed again. Longer than any job’s timeout. Default 90. |
queue.poll_seconds | How long an idle worker waits before looking again. Default 1. |
Run a worker apart
#[tokio::main]
async fn main() -> anyhow::Result<()> {
Bootstrap::new("config")
.module(migrations::AppModule)
.run()
.await
}
lat queue work # cargo run -- queue work
lat queue work --once
lat queue work --stop-when-empty --queue high,default
acme queue work # the built binary
Bootstrap::run reads the process’s arguments: serve (the default), queue work or schedule run. With queue.mode = "external", the serving process runs no worker.
Act on the failed list
lat queue list
lat queue failed
lat queue retry 42
lat queue retry all
lat queue forget 42
lat queue flush --queue mail
use laterite_core::queue::JobFailed;
use laterite_core::{EventCx, EventError, Listener};
struct Alert;
#[laterite_core::strata::async_trait]
impl Listener<JobFailed> for Alert {
async fn handle(&self, cx: &EventCx<'_>, failed: &JobFailed) -> Result<(), EventError> {
acme::alerts::record(cx.db(), &failed.name, &failed.error).await?;
Ok(())
}
}
fn register(&self, registry: &mut Registry) {
registry.listen::<JobFailed>(Alert);
}
A job reaching the failed list announces queue.job_failed with its id, name, queue, attempts and error.
Grant the Jobs screen
# a role's permissions
- backend.manage_jobs
| Permission | Grants |
|---|---|
backend.manage_jobs | Settings → System → Jobs: the waiting and running counts per queue, the failed list with each job’s payload and error, Retry and Forget for one job or all. |
Test a job
let queue = Queue::inline(vec![JobReg::of::<SendDigest>()], services);
assert_eq!(queue.push(&SendDigest { user_id: 7 }).await?, Pushed::Ran);
# config/test.toml
[queue]
mode = "inline"
Scheduler
An entry names a cron expression and what to do; the application evaluates every entry each minute, in the entry’s timezone, on one process of the deployment.
use laterite_core::schedule::{Overlap, ScheduleEntry, ScheduleRegistry};
fn register(&self, registry: &mut Registry) {
registry.add_schedule(
ScheduleEntry::new("acme.blog::digest", "0 7 * * *")
.timezone("Europe/Berlin")
.description("Send the daily digest.")
.job(SendDigest { user_id: 0 }),
);
registry.add_schedule(
ScheduleEntry::every_minutes("acme.blog::sweep", 5)
.run(|cx| async move { sweep(cx.db()).await }),
);
}
| Constructor | Expression |
|---|---|
ScheduleEntry::new(name, expression) | Five fields (0 7 * * *), six with seconds, or @hourly, @daily, @weekly, @monthly, @yearly. |
ScheduleEntry::every_minutes(name, n) | */n * * * * |
ScheduleEntry::hourly(name) | 0 * * * * |
ScheduleEntry::daily_at(name, "07:30") | 30 7 * * * |
| Method | Default | Meaning |
|---|---|---|
.run(|cx| async { .. }) | Runs the closure when due; cx gives db(), events(), cache(), parameters(), queue(). | |
.job(job) | Pushes the job when due. | |
.timezone("Asia/Colombo") | UTC | The timezone the expression is read in. |
.description("..") | A line for the Scheduled tasks screen. | |
.overlap(Overlap::Allow) | Overlap::Skip | Whether a due entry runs while its last run is still going. |
.one_server(false) | true | Whether one process of the deployment runs it per minute, or every process does. |
An entry with a bad expression or timezone, without .run or .job, or with a name already taken is refused when the application boots.
Configure the ticker
# config/default.toml
[schedule]
mode = "ticker" # ticker | external | off
| Key | Description |
|---|---|
schedule.mode | ticker evaluates the entries in the application process; external leaves it to schedule run; off evaluates nothing. |
Run the ticker apart
lat schedule run # cargo run -- schedule run
lat schedule run --once # this minute's entries, then exit
acme schedule run # the built binary
* * * * * cd /srv/acme && ./acme schedule run --once
Bootstrap::run reads the process’s arguments: serve (the default), queue work or schedule run.
Read the last runs
lat schedule list
for entry in ctx.schedule().list().await? {
println!("{} next {:?} last {:?}", entry.name, entry.next_run_at, entry.last_status);
}
ctx.schedule().run_now("acme.blog::digest").await?;
| Field | Holds |
|---|---|
name, expression, timezone, description | The entry as declared. |
next_run_at | The next due minute, UTC. |
last_started_at, last_finished_at | The last run’s bounds, UTC. |
last_status | never, running, ok, failed or skipped. |
last_error | The last run’s error, when it failed. |
run_now(name) runs an entry outside its expression, under the same locks; false when it was skipped.
Grant the Scheduled tasks screen
# a role's permissions
- backend.manage_schedule
| Permission | Grants |
|---|---|
backend.manage_schedule | Settings → System → Scheduled Tasks: every entry with its expression, timezone, next and last run, status and error, and Run now. |
Entries the framework registers
| Entry | Expression | Does |
|---|---|---|
laterite.auth::purge | 0 * * * * | Removes expired sessions and stay-signed-in credentials. |
A message names a template and its variables, or carries its own subject and body; send queues it and a worker delivers it through the configured driver.
use laterite_core::mail::Message;
ctx.mail()
.send(
Message::template("acme.blog::welcome", serde_json::json!({ "name": "Ada", "link": url }))
.to("Ada <ada@acme.example>"),
)
.await?;
| Method | Does |
|---|---|
Message::template(code, vars) | A message rendered from the template code. |
Message::raw(subject, text, html) | A message with its own body; html optional. |
.to(addr), .cc(addr), .bcc(addr), .reply_to(addr), .from(addr) | Addresses, as Name <address> or bare. |
.attach(filename, content_type, bytes) | A file. |
mail.send(message) | Queues it; Pushed::Ran in inline mode. |
mail.send_now(message) | Renders and delivers here, returning the driver’s error. |
mail.envelope(message) | What the driver would deliver, rendered and addressed; nothing is sent. |
mail.send_test(addr) | The built-in test template, delivered here. |
Register a template
use laterite_core::mail::MailRegistry;
fn register(&self, registry: &mut Registry) {
registry.add_mail_template("acme.blog::welcome", include_str!("../mail/welcome.htm"));
registry.add_mail_layout("acme", include_str!("../mail/layouts/acme.htm"));
registry.add_mail_partial("signature", include_str!("../mail/partials/signature.htm"));
}
---
subject: Welcome, {{ name }}
layout: default
description: Sent when an account is made.
---
# Hello {{ name }}
Your account on **{{ app_name }}** is ready.
{% set body %}Sign in{% endset %}
{{ partial("button", url=link, body=body) }}
| Part | Holds |
|---|---|
| Front matter | subject, layout (default unless set), description; a layout or partial has name. |
| Body | A template’s body, written as Markdown; a layout’s or partial’s, as HTML. |
The plain-text part is made from the body, with each partial’s text form. A
message that needs its own text part registers a .txt beside the .htm:
registry.add_mail_template_with_text(
"acme.blog::welcome",
include_str!("../mail/welcome.htm"),
include_str!("../mail/welcome.txt"),
);
Welcome {{ name }}.
{{ partial("button", url=link, body="Sign in") }}
A layout’s text wrapper and a partial’s text form register the same way
(add_mail_layout_with_text, add_mail_partial_with_text). A layout’s CSS
goes in a <style> element in its HTML, reading the brand as
{{ brand.button_bg }}.
The older form, a key = "value" header and sections split by a line of
== (text, HTML, CSS), still reads and is logged as deprecated.
A layout receives content, subject, app_name, css and brand_css. An undefined variable renders empty. A template edited in the admin keeps its edit until it is reset to the file.
| Template | Sent by |
|---|---|
laterite::test | The Mail settings’ Send test and lat mail test. |
laterite.auth::invite | Creating an operator; name, username, link, expires. |
laterite.auth::reset | The Forgot your password page; name, username, link, expires. |
| Partial | Arguments |
|---|---|
button | url, body |
panel, table, subcopy | body, Markdown |
header, footer | body, url (header only) |
Configure the transport
# config/default.toml
[mail]
driver = "smtp" # smtp | log | stub | a registered driver
from = "Acme <no-reply@acme.example>"
# to = "dev@acme.example" # every message goes here while set
[mail.smtp]
host = "smtp.acme.example"
port = 587
encryption = "starttls" # starttls | tls | none
username = "apikey"
password = "" # or LAT__MAIL__SMTP__PASSWORD
timeout_seconds = 30
| Key | Description |
|---|---|
mail.driver | smtp (the smtp feature of laterite-core, on in lateritecmf), log (kept in the mail log, nothing leaves), stub (kept in memory) or a driver a module registered. Default log. |
mail.from | The sender. Default Laterite <no-reply@localhost>. |
mail.to | A development override: every message goes to this address instead of its recipients. |
mail.smtp.* | The server, port, encryption, credentials and timeout. |
The Mail settings under Settings → System → Mail lay over these: a blank field keeps the configured value, the password is sealed under the application key, and a save switches the transport at once. Gated by backend.manage_mail.
lat mail test ada@acme.example
Send a test message to me on the settings screen mails the signed-in operator the built-in laterite::test template and shows the driver’s error when it fails.
Edit templates in the admin
# a role's permissions
- backend.manage_mail_templates
- backend.manage_mail
| Permission | Grants |
|---|---|
backend.manage_mail_templates | Settings → System → Mail Templates: the templates, layouts and partials with a preview, a test send to the signed-in operator, Reset to the file, Delete for one no file registers, and New; Mail Branding: the colours every layout reads, with a preview on the test template. |
backend.manage_mail | Mail (the sender and transport, Send a test message) and Mail Log: the messages the log driver kept, each as text and as HTML, with Clear. |
| Brand colour | Layout property |
|---|---|
| Page background, content background, panel background | brand.body_bg, brand.content_bg, brand.panel_bg |
| Header text, headings, text, muted text, footer text | brand.header_color, brand.heading_color, brand.text_color, brand.muted_color, brand.footer_color |
| Links, button, button text, borders | brand.link_color, brand.button_bg, brand.button_text_color, brand.border_color |
Register a driver
use laterite_core::mail::{MailDriverReg, MailRegistry, Mailer};
fn register(&self, registry: &mut Registry) {
registry.add_mail_driver(MailDriverReg::new("acme-http", |config, _db| {
Ok(Arc::new(AcmeHttp::new(&config.smtp.username)))
}));
}
A driver implements Mailer: a name() and deliver(&Envelope); mail.driver = "acme-http" or the settings screen selects it.
Media Library
The Media tab holds the files a site and its records use: folders, upload,
search, a kind filter and a page per file. Opening it takes media.browse.
| Permission | Grants |
|---|---|
media.browse | The tab. |
media.upload | Upload into it. |
media.manage | Rename, retitle, move and crop, and make or remove folders. |
media.delete | Delete a file no record links to. |
media.delete_linked | Delete a file records still use; the file page lists them. |
Grant them from a role like any other permission.
Upload
# config/default.toml
[backend]
upload_extensions = ["jpg", "jpeg", "png", "webp", "svg", "pdf", "css"]
A file whose extension is not listed is refused; an empty list allows images,
documents, audio, video, fonts and archives. An SVG is cleaned on the way in.
Library uploads go to the disk named public, else media under
backend.storage (see Storage Disks).
Ticking Private sends them to the disk named private, else private
under backend.storage.
| File | Served at |
|---|---|
| Public | /storage/media/<hash>/<name>, cacheable. |
| Private | /admin/media-files/<id>/<name>, signed in, for whoever may browse the library or see a record the file is attached to; see Storage disks. A tile carries a lock. |
Find a file
| Control | Narrows to |
|---|---|
| Folder | The files in it. |
| Search | A name, across every folder. |
| Kind | Image, Video, Audio, Document, Font or Other; Font is listed once the library holds a font. |
| Sort | Newest, oldest, name or size. |
Manage folders and files
| Action | Where | Needs |
|---|---|---|
| Make, rename, move or remove a folder | The folder bar | media.manage; an empty folder only. |
| Retitle, rename or move a file | The file page | media.manage |
| Crop an image | The file page | media.manage; a new file <stem>-crop.<ext> beside it, or the file replaced. |
| Make private, make public | The file page | media.manage; the file moves disk and its thumbnails are made again. |
| Delete a file | The file page | media.delete, or media.delete_linked when records use it. |
Work the library from code
use laterite_media::library::{self, Listing, Sort};
use laterite_media::{folder, record, Kind};
let photos = folder::create(&db, None, "Photos").await?;
let year = folder::create(&db, Some(photos.id), "2026").await?; // path /Photos/2026
folder::rename(&db, year.id, "2027").await?;
folder::move_to(&db, year.id, None).await?;
folder::delete(&db, year.id).await?; // empty folders only
let crumbs = folder::ancestors(&db, year.id).await?;
let page = library::list(&db, &Listing {
folder: Some(photos.id),
search: None,
kind: Some(Kind::Image),
sort: Sort::Newest,
page: 1,
per_page: 60,
}).await?;
record::update_details(&db, id, Some("Our cat"), Some("A tabby")).await?;
record::rename(&db, id, "cat.png").await?;
record::move_to_folder(&db, id, Some(photos.id)).await?;
let has_fonts = library::has_kind(&db, Kind::Font).await?;
let unused = record::set_disk(&db, id, "private").await?; // after copying the blob
record::set_in_library(&db, id, true, None).await?;
| Call | Refused when |
|---|---|
folder::create, folder::rename | The name has a slash or a control character, or a sibling has it. |
folder::move_to | The target is the folder or below it. |
folder::delete | The folder still holds a file or a folder. |
Listing.search looks across every folder; Kind::of(content_type) gives
Image, Video, Audio, Document or Other.
Media Field
A media field holds one file, or a list of files, picked from the
library.
fields:
cover_id: { type: media, label: Cover, mode: image }
gallery: { type: media, label: Gallery, max: 6 }
fonts: { type: media, label: Fonts, mode: font, max: 0 }
logo_id: { type: media, label: Logo, mode: image, public: true }
| Option | Default | Meaning |
|---|---|---|
mode | file | image offers images alone and shows thumbnails; font offers font files alone. |
max | 1 | How many files the field holds: 1 stores one id in a bigint column; any other number stores a JSON list in a text column, 0 meaning no limit. |
public | false | The file is shown to people who are not signed in: the picker marks a private file and does not take it, a save refuses one, and a file the field holds cannot be made private. |
A save links the picked files to the record under the field’s name; a
settings screen links them to its code. The file page lists the screens and
fields that use a file, and deleting such a file needs media.delete_linked.
| Event | Detail |
|---|---|
lat:media:changed | {ids}, after a pick, a removal or a clear. |
Link records from code
use laterite_media::{link, Owner};
let owner = Owner { owner_type: "acme_posts", owner_id: "7", field: "gallery" };
link::set(&db, owner, &media_ids).await?; // in that order
let held = link::of_owner(&db, owner).await?;
let users = link::users_of(&db, first).await?;
link::clear_owner(&db, "acme_posts", "7").await?;
| Call | Does |
|---|---|
link::set(db, owner, media_ids) | Replaces what the owner’s field holds with media_ids, in that order. |
link::of_owner(db, owner) | The ids the owner’s field holds. |
link::users_of(db, id) | Every owner linking the file. |
link::clear_owner(db, owner_type, owner_id) | Drops every link a record holds. |
Direct Uploads
A direct upload sends the bytes from the browser straight to a disk that presigns, and the application records the file once it has landed.
POST /admin/media/direct name=clip.mp4&content_type=video/mp4&size=52428800
→ {"direct": true, "url": "<presigned PUT>", "path": "quarantine/<id>/clip.mp4", "headers": {"Content-Type": "video/mp4"}}
PUT <presigned PUT> the bytes, from the browser
POST /admin/media/direct/complete path=quarantine/<id>/clip.mp4&name=clip.mp4&folder=3
→ {"stored": [{"id": 7, "name": "clip.mp4", "href": "/admin/media/7", "url": "..."}], "refused": []}
| Step | On a disk that presigns | On any other disk |
|---|---|---|
direct | A PUT URL under quarantine/<32 hex>/<name>, good for an hour. | {"direct": false}: the uploader posts the file instead. |
complete | The object is checked, recorded and removed from quarantine/. | The same, for an object already under quarantine/. |
Turn it on
The upload zone does this on its own when it carries upload_direct, the URL
of the direct route (see Receive an
upload). The library’s own
upload carries it. A path outside quarantine/, or an object larger than the
upload limit, is refused.
Abandoned quarantine objects are the bucket’s to expire: set a lifecycle rule
of one day on the quarantine/ prefix.
Presign from a driver
| Method | Default | On S3Disk |
|---|---|---|
StorageDriver::presigned_put(path, content_type, expires_in) | None | A presigned PUT. |
StorageDriver::copy(from, to) | get then put | A server-side copy. |
A driver returning None from presigned_put answers {"direct": false}.
Image Variants
A preset names a size and format an image serves at; the variant renders on its first request.
use laterite_media::{Format, Preset};
registry.add(Preset::new("card").width(600).height(400).crop());
registry.add(Preset::new("hero").width(1600).format(Format::WebP).quality(85));
<img src="/storage/media/{{ hash }}/card/{{ name }}" width="600" height="400">
| Builder | Default | Meaning |
|---|---|---|
Preset::new(name) | The name in the URL. | |
.width(px), .height(px) | unbounded | The box. |
.fit() | yes | Inside the box, keeping the aspect ratio; a smaller source stays its size. |
.crop() | Filling the box, cropped from the centre. | |
.exact() | The box, stretched. | |
| `.format(Format::Auto | Jpeg | Png |
.quality(1..=100) | 82 | JPEG quality. |
Override a built-in preset
| Built in | Box | Used by |
|---|---|---|
thumb | 320 × 320, fit | The library grid. |
preview | 1200 × 1200, fit | The file page. |
A registered preset with a built-in name replaces it. An undeclared name is a 404. A file that is not an image serves as it is under any preset.
Keep within the limits
| Limit | Value |
|---|---|
| Side | 12 000 pixels. |
| Pixels | 50 million. |
An image past either limit serves as it is. A variant renders upright,
whatever orientation the camera recorded; width and height are recorded
on upload.
Render from code
let prepared = laterite_media::image::prepare(bytes);
let rendered = laterite_media::image::render(&bytes, &preset, prepared.orientation)?;
let made = variants.ensure(&db, disk.as_ref(), &record, &preset).await?;
Crop an image
POST /admin/media/<id>/crop x=100&y=50&w=200&h=100&mode=new
| Field | Meaning |
|---|---|
x, y, w, h | The area kept, in the image’s own pixels, clamped to it. |
mode | new (the default): a file named <stem>-crop.<ext> in the same folder. replace: this file changes in place and its variants are dropped. |
The format is kept (PNG, JPEG, WebP; anything else becomes PNG). The file page
offers the dialog on an image to a user with media.manage.
let out = laterite_media::image::crop(&bytes, Rect { x, y, width, height }, orientation)?;
laterite_media::record::replace_blob(&db, id, &hash, size, &content_type, width, height).await?;
Maintenance
lat media removes files nothing links to and checks every stored file
against its record.
lat media gc # files outside the library that nothing links to
lat media gc --grace 1 # younger than one hour is left alone (default 24)
lat media gc --dry-run # list, remove nothing
lat media verify # check every stored file against its record
| Flag | Default | Meaning |
|---|---|---|
--grace <hours> | 24 | A record younger than this is never garbage. |
--dry-run | off | Prints id, disk, hash and name; removes nothing. |
--storage <dir> | backend.storage | Where the media and private disks live. |
Collect garbage
A file is removed with the last record naming it. A record on a disk the command cannot reach (one the application registered itself) is skipped and counted. From code:
let report = laterite_media::gc::collect(&db, &disks, chrono::Duration::hours(24)).await?;
Verify stored files
verify exits non-zero on a fault and prints one line per faulty record:
missing, content mismatch, or a size the record disagrees with. From code:
let report = laterite_media::verify::run(&db, &disks).await?;
Delete a record
if laterite_media::record::delete(&db, id).await? {
disk.delete(&blob_path(&hash)).await?;
}
delete returns whether the file is now unreferenced. Deleting a file already
gone succeeds.
Themes
A theme is a set of templates edited from the admin and served as the site; this page covers the module, the Themes screen, a theme’s config and preview image, its templates and revisions, and the active and edit theme. Register the module and its tables migrate with the application’s:
use lateritecmf::prelude::*;
use lateritecmf::web::theme::ThemeModule;
Bootstrap::new("config")
.module(ThemeModule)
.module(migrations::AppModule)
.run()
.await
Create a theme from its YAML config, add templates, and make it the site’s theme:
use lateritecmf::web::theme::{self, store, Kind};
let site = store::create_theme(&db, "acme", "name: Acme\nauthor: Acme\n").await?;
store::save_template(&db, site.id, Kind::Layout, "default.htm", None, LAYOUT, None).await?;
store::save_template(
&db,
site.id,
Kind::Page,
"home.htm",
Some(serde_json::json!({ "url": "/", "layout": "default" })),
HOME,
Some(operator_id),
)
.await?;
theme::set_active_theme(&db, "acme").await?;
Mount the screen
ThemeModule registers the Themes tab at /admin/themes under the permission web.manage_themes, granted to the Administrator role.
| Setting | Default | Meaning |
|---|---|---|
backend.paths."laterite.theme/themes" | /themes | Where the tab mounts under the admin, as a deployment override. |
A module’s own screen audits through the route context:
ctx.audit(&user, "acme.thing.save", Some("thing"), Some(&id), Some(&label), None).await;
Write the config
name: Acme
author: Acme
homepage: https://acme.example
description: The Acme site.
parent: base
require:
- acme.blog
form:
fields:
site_name:
label: Site name
default: Acme
| Key | Type | Default | Meaning |
|---|---|---|---|
name | string | "" | The theme’s display name. |
author | string | "" | Who made it. |
homepage | string | "" | The author’s site. |
description | string | "" | One line about the theme. |
preview | string | none | A URL for the image on the theme list; the initials stand in without one. |
parent | string | none | The theme whose templates fill in for the ones this theme lacks (see Child Themes). |
require | list of module ids | [] | The modules the theme’s templates need. |
form | form descriptor | none | The theme’s own settings fields (see Theme Settings and Form Descriptor). |
A key outside this table is refused. ThemeConfig::parse reads the YAML and ThemeConfig::to_yaml writes it.
Add a preview image
name: Acme
preview: https://acme.test/themes/acme/preview.png
| Property | Standard |
|---|---|
| Size | 1200 × 800 pixels. Minimum 600 × 400. |
| Aspect | 3:2, exactly. |
| Format | PNG or JPEG. WebP is accepted. |
| Weight | Under 300 KB. |
| Subject | The home page as the theme renders it, cropped from the top of the viewport at 1200 pixels wide. |
| Framing | No browser chrome, device frame, drop shadow, border or rounded corners: the image edges are the page edges. |
| Overlays | No added text, badges, logos or colour swatches. |
| Content | Representative content and real images; no placeholder blocks. |
| Colour scheme | Light, unless the theme is dark only. |
| Transparency | None: an opaque image. |
| Shown at | 184 pixels wide on the theme list, so headings and large shapes must still read at that size. |
A theme without preview shows its initials on the theme list.
Save a template
| Kind | Path | Holds |
|---|---|---|
Kind::Layout | layout | The frame a page renders inside (see Layouts and Partials). |
Kind::Page | page | A page served at its URL (see Pages). |
Kind::Partial | partial | A fragment a layout or page includes. |
Kind::Content | content | A block of HTML, Markdown or text (see Content). |
Kind::Asset | asset | A text file the site serves (a stylesheet, a script). |
A path is /-separated segments of lowercase letters, digits, dots, hyphens and underscores, at most 255 characters. settings is a JSON object; None keeps the current one.
// A theme's own templates, or those of one kind.
let all = store::list_templates(&db, site.id, None).await?;
let pages = store::list_templates(&db, site.id, Some(Kind::Page)).await?;
store::delete_template(&db, template.id).await?;
| URL | Serves |
|---|---|
/themes/<code>/assets/<path> | The theme’s text asset, rendered, with an ETag and public, no-cache. |
Restore a revision
Every save keeps what it replaced:
let revisions = store::revisions(&db, template.id).await?; // newest first
let restored = store::restore_revision(&db, revisions[0].id, Some(operator_id)).await?;
Manage themes
let all = store::list_themes(&db).await?;
let one = store::find_theme(&db, "acme").await?;
store::update_theme_config(&db, "acme", "name: Acme\nparent: base\n").await?;
store::set_locked(&db, "acme", true).await?;
let copy = store::duplicate_theme(&db, "acme", "acme-copy").await?;
let child = store::create_child_theme(&db, "acme", "acme-child", "Acme child").await?;
store::delete_theme(&db, "acme-copy").await?;
| Call | Refused when |
|---|---|
create_theme | The code is taken, is not lowercase letters, digits and hyphens, or the parent is missing or leads back to the theme. |
update_theme_config | The theme is locked, or the parent is missing or leads back. |
save_template, delete_template | The theme is locked, or the path is not a template path. |
delete_theme | The theme is active, locked, or another theme’s parent. |
Set the active and edit theme
theme::set_active_theme(&db, "acme").await?;
let live = theme::active_theme(&db).await?;
theme::set_edit_theme(&db, operator_id, Some("acme-next")).await?;
let editing = theme::edit_theme(&db, operator_id).await?; // the operator's choice, else the active theme
theme::set_edit_theme(&db, operator_id, None).await?;
A visitor sees the active theme. A user signed in to the admin with web.manage_themes sees their edit theme and its hidden pages, and reads this.preview as true (see Properties).
Replace the site
ThemeModule serves the active theme’s pages at every URL the admin and the other public routes leave. A module of your own takes the site’s place through PublicRouteReg::site:
registry.add_public_route(PublicRouteReg::site(Arc::new(MySite)));
let operator = ctx.operator(&headers).await; // the session cookie's operator, if any
let person = ctx.identity(user_id).await; // an active operator by id, for a token the route issued
ctx.record_unserved("GET", "/missing", 404).await; // into the request log
Pages
A page is a template served at its URL; its settings name the URL pattern, the layout, the head’s meta fields and whether it is hidden.
{
"url": "/blog/:slug",
"layout": "default",
"title": "A post",
"description": "",
"meta_title": "",
"meta_description": "",
"meta_image": "",
"meta_type": "",
"meta_robots": "",
"hidden": false
}
| Key | Default | Meaning |
|---|---|---|
url | required | The URL pattern. |
layout | none | The layout by name (default for layouts/default.htm); the page then fills its page block, and a block the page defines at its top level fills the layout’s block of that name without rendering in place. A page that writes {% extends %} itself is left as written. |
title, description | "" | The page’s own words, read as this.page.title. |
meta_title, meta_description, meta_image, meta_type, meta_robots | "" | The head’s meta fields. |
hidden | false | Served only to an operator previewing the theme. |
components | none | The components attached to the page, by alias (see Components). |
The save refuses a pattern that does not parse or a layout the theme and its ancestors lack.
Write a URL pattern
| Pattern | Matches |
|---|---|
/blog | /blog, in any case |
/blog/:slug | one segment, bound to slug |
/blog/:slug? | the segment or nothing |
/blog/:page?1 | the segment, or 1 when left out |
| `/blog/:id | ^[0-9]+$` |
/docs/:path* | one or more segments, joined with / |
/docs/:path?* | none or more segments |
An optional parameter before a required one is required. One wildcard at most, with no expression and nothing optional after it. The most specific page wins: more static segments, then fewer wildcards, then fewer parameters. The parameters are read as this.params (see Properties).
Link to a page
{% block title %}{{ this.page.title }}{% endblock %}
<a href="{{ page('blog/post', slug=post.slug) }}">{{ post.title }}</a>
| Name | Gives |
|---|---|
page(<name>, param=value, ...) | The URL of the page named by its path without the extension; a parameter left out takes its default. |
{% block page %} in a layout | Where the page renders (see Layouts and Partials). |
The other functions are listed under Functions.
Resolve a URL from Rust
let engine = Engine::build(&db, "acme").await?;
if let Some((name, params)) = engine.resolve("/blog/hello") {
let settings = engine.page(name);
let url = engine.url_for(name, ¶ms);
}
for (name, url) in engine.routes().fixed() {
println!("{name} at {url}");
}
router::Pattern::parse, Pattern::matches, Pattern::url and router::RouteTable are the engine beneath, usable on their own.
Serve the error pages
| Page at | Serves |
|---|---|
/404 | An unmatched URL, with status 404. |
/error | A page that failed to render, with status 500. |
Hide a page
{ "url": "/drafts", "layout": "default", "hidden": true }
A hidden page is served only to a user previewing their edit theme, and the static build skips it.
Layouts and Partials
A layout is the frame a page renders inside; a partial is a fragment a layout or page includes.
{# layouts/default.htm #}
<!doctype html>
<html>
<head>{{ head }}</head>
<body>
{% include "partials/nav.htm" %}
<main>{% block page %}{% endblock %}</main>
</body>
</html>
{# pages/home.htm, with the settings {"url": "/", "layout": "default"} #}
{% block title %}{{ this.page.title }}{% endblock %}
<h1>{{ this.page.title }}</h1>
{{ partial("card.htm", title="Acme", body=page.body) }}
| Name | Gives |
|---|---|
layout in a page’s settings | The layout by name (default for layouts/default.htm); the page then fills its page block, and a block the page defines at its top level fills the layout’s block of that name without rendering in place. A page that writes {% extends %} itself is left as written. |
{% block page %} in a layout | Where the page renders. |
{% extends "layouts/<path>" %}, {% block %} | A page inside a layout. |
{% include "partials/<path>" %} | A partial with the current variables. |
partial(<path>, name=value, ...) | A partial with the named variables, the request’s this and head, and the globals. |
Name a template
| Kind | Name |
|---|---|
Kind::Layout | layouts/default.htm |
Kind::Page | pages/home.htm |
Kind::Partial | partials/nav.htm |
Kind::Asset | assets/css/site.css |
A theme’s own template is used, else the nearest ancestor’s (see Child Themes).
Save a layout or partial from Rust
store::save_template(&db, site.id, Kind::Layout, "default.htm", None, LAYOUT, None).await?;
store::save_template(&db, site.id, Kind::Partial, "nav.htm", None, NAV, None).await?;
The path rules and the other calls are under Themes.
Give a partial a role
| Partial at | Role |
|---|---|
partials/<alias>/default.htm | The markup of the component attached under <alias> (see Components). |
partials/<code>/default.htm | The markup of the component offered as the snippet <code> (see Snippets). |
A partial with snippet in its settings | An insertable block in the rich and markdown editors (see Snippets). |
Content
A content block is a file of HTML, Markdown or text a template inserts with content(); the content filter expands snippets in stored HTML.
{{ content("intro.md") }}
{{ content("welcome.htm", name=this.params.name) }}
{{ post.body|content }}
{# content/welcome.htm #}
<p>Welcome, {name}.</p>
| Name | Gives |
|---|---|
content(<path>, name=value, ...) | A content block: .md rendered to HTML, .htm and .html as they are, anything else escaped as text; {name} in the block is the named variable, escaped. |
<html>|content | Snippets in stored HTML expanded (see Snippets); content(<path>) does the same for a block. |
| Extension | Rendered as |
|---|---|
.md | HTML, as the markdown filter renders it. |
.htm, .html | As written. |
| Any other | Text, escaped. |
Save a content block from Rust
store::save_template(&db, site.id, Kind::Content, "intro.md", None, "# Welcome\n", None).await?;
The path rules and the other calls are under Themes.
Components
A module ships a component; a page or layout attaches it in its settings under components, keyed by the alias the template reads it as.
use lateritecmf::web::theme::component::{
Component, ComponentContext, ComponentOutput, ComponentReg, PropertyDef, PropertyKind,
};
use lateritecmf::web::theme::ThemeError;
use std::sync::Arc;
struct Posts;
#[lateritecmf::core::strata::async_trait]
impl Component for Posts {
fn properties(&self) -> Vec<PropertyDef> {
vec![
PropertyDef::new("limit", "How many", PropertyKind::Number).default(5),
PropertyDef::new("slug", "Slug", PropertyKind::Text),
]
}
async fn run(&self, cx: &ComponentContext<'_>) -> Result<ComponentOutput, ThemeError> {
let limit = cx.properties["limit"].as_u64().unwrap_or(5);
let items = load_posts(cx.db, limit).await?;
Ok(ComponentOutput::data(serde_json::json!({ "items": items }))
.inject("site_name", "Acme"))
}
}
fn register(&self, registry: &mut Registry) {
registry.add(ComponentReg::new("acme.posts", "Posts", Arc::new(Posts)));
}
{
"url": "/blog/:slug",
"layout": "default",
"components": {
"post": { "component": "acme.posts", "limit": 1, "slug": "{{ :slug }}" },
"latest": { "component": "acme.posts" }
}
}
<h1>{{ post.items[0].title }}</h1>
{% for item in latest.items %}<li>{{ item.title }}</li>{% endfor %}
<footer>{{ site_name }}</footer>
| Name | Gives |
|---|---|
properties() | The properties an attachment may set, with kind, required and default; the save refuses an unknown component, an undeclared property, a wrong kind or a missing required one. |
run() | ComponentOutput::data, read under the alias, and .inject(name, value) for the page scope. |
cx.properties | The attached values, {{ :name }} resolved from the URL and defaults filled. |
cx.db, cx.params, cx.path, cx.theme, cx.preview | The request. |
A layout’s components run first, then the page’s; a page alias replaces a layout’s.
Ship markup with a component
A component may ship markup; a theme overrides it per alias:
fn markup(&self) -> Option<&'static str> {
Some("<ul>{% for item in component.items %}<li>{{ item.title }}</li>{% endfor %}</ul>")
}
{{ component('latest') }}
| Name | Gives |
|---|---|
component(<alias>) | The theme’s partials/<alias>/default.htm, else the component’s own markup, with the data as component and under the alias, beside this and head. |
Offer a component as a snippet
ComponentReg::snippet lists the component in the editors’ Insert menu; see Snippets.
Build a static site with components
build::build_with takes the registered components for a static build; see Static Build.
Snippets
A snippet is an insertable block in the rich and markdown editors, backed by a partial or by a component.
{
"snippet": {
"code": "youtube",
"name": "YouTube video",
"description": "Embeds a video by its URL",
"properties": [
{ "code": "url", "title": "Video URL", "type": "string" },
{ "code": "size", "title": "Size", "type": "dropdown", "options": "sm:Small | lg:Large", "default": "sm" },
{ "code": "autoplay", "title": "Autoplay", "type": "checkbox", "default": false }
]
}
}
{# partials/snippets/youtube.htm #}
<iframe src="https://www.youtube.com/embed/{{ url|replace("https://www.youtube.com/watch?v=", "") }}{% if autoplay %}?autoplay=1{% endif %}" class="video video--{{ size }}"></iframe>
{{ post.body|content }}
| Key | Values | Default |
|---|---|---|
code | letters, digits, ., -, _ | required |
name, description | shown in the Insert menu | description optional |
properties[].code | the variable name in the partial | required |
properties[].title | the dialog’s label | required |
properties[].type | string, dropdown, checkbox | string |
properties[].default | the value when unset | none |
properties[].options | value:Label | value2:Label2 for a dropdown | none |
Declare a snippet on a partial
A partial becomes a snippet through the snippet key of its settings, as above. In the HTML an editor saves, an inserted snippet is <figure data-snippet="youtube" data-properties="{...}"></figure>; \|content renders the partial with each property as a variable beside this and head. A snippet no partial declares renders as an HTML comment naming it.
Declare it from the partial page
The partial’s page carries the declaration as fields under Snippet.
| Field | Writes |
|---|---|
| Code | snippet.code; blank withdraws the snippet. |
| Name, Description | snippet.name, snippet.description |
| Properties | One row per property: Code, Title, Type, Default, Options. A checkbox default of true, 1, on or yes is stored as true. |
Back a snippet with a component
registry.add(
ComponentReg::new("acme.map", "Map", Arc::new(Map))
.snippet("Map", Some("A map centred on an address")),
);
{# partials/acme.map/default.htm, else the component's own markup #}
<div class="map" data-lat="{{ component.lat }}" data-lng="{{ component.lng }}"></div>
| Step | Does |
|---|---|
.snippet(name, description) | Lists the component in the Insert menu; its properties are the dialog’s fields (Bool a checkbox, the rest text). |
|content | Leaves the figure in place. |
| After the page renders | Each distinct figure runs the component with its properties (text read to the declared kinds) and renders partials/<code>/default.htm, else the component’s markup, with component, the code, this and head. |
| A failure | An HTML comment naming the snippet. |
The component’s properties and markup are described under Components.
Theme Settings
A theme declares its own settings under form in the config; the theme page shows them as a form, and templates read the values beside the theme’s keys.
name: Acme
form:
fields:
site_name:
label: Site name
type: text
tagline:
label: Tagline
type: textarea
<h1>{{ theme.site_name }}</h1>
<p>{{ theme.tagline }}</p>
| Key | Meaning |
|---|---|
form | A form descriptor (see Form Descriptor); the fields are listed under Form Fields. |
theme.<field> | The saved value, read in any template beside theme.code, theme.name, theme.author, theme.homepage and theme.description (see Properties). |
A child theme without a form uses its parent’s; the values are each theme’s own. A field named code, name, author, homepage or description is refused.
Read and save the values from Rust
let chain = store::chain(&db, "acme").await?;
let fields = store::form_fields(&chain);
store::save_settings(&db, "acme", &serde_json::json!({ "site_name": "Acme" })).await?;
let values = store::find_theme(&db, "acme").await?.unwrap().settings;
Render the form on a module screen
A module’s own screen renders and collects such a form through the route context:
let form = ctx.value_form(&fields, "acme")?;
let markup = form.render(&values, &shell);
let saved = form.collect(&data)?;
let page = shell.page_with(PageHead::new(title).assets(&form.assets()), markup);
form.assets() lists the scripts and styles the fields’ types declare; pass
them to the page head.
Child Themes
A child theme names a parent in its config and uses the parent’s templates for the ones it lacks.
name: Acme child
parent: acme
let child = store::create_child_theme(&db, "acme", "acme-child", "Acme child").await?;
| Key | Type | Default | Meaning |
|---|---|---|---|
parent | string | none | The theme whose templates fill in for the ones this theme lacks. |
| Lookup | Result |
|---|---|
| A template by kind and path | The theme’s own, else the nearest ancestor’s. |
A page’s layout | Any layout of the theme or its ancestors. |
The settings form | The theme’s own, else its parent’s; the values are each theme’s own (see Theme Settings). |
Resolve a template through the chain
// Through the parent chain: the theme's own row, else the nearest ancestor's.
if let Some((from, template)) = store::resolve_template(&db, "child", Kind::Layout, "default.htm").await? {
println!("{} from {}", template.path, from.code);
}
let chain = store::chain(&db, "child").await?;
Change or remove a parent
store::update_theme_config(&db, "acme-child", "name: Acme child\nparent: base\n").await?;
| Call | Refused when |
|---|---|
create_theme | The parent is missing or leads back to the theme. |
update_theme_config | The theme is locked, or the parent is missing or leads back. |
delete_theme | The theme is another theme’s parent. |
The other calls are under Themes.
Export and Import
A theme travels as a zip of its config, settings values and templates, written by lat theme export and read by lat theme import.
lat theme list
lat theme export acme
lat theme export acme --out themes/acme.zip
lat theme import acme themes/acme.zip
lat theme import acme themes/acme.zip --replace
acme.zip
├── theme.yaml
├── settings.json # the theme's settings values, when it has any
├── layouts/default.htm
├── pages/home.htm
├── partials/nav.htm
├── content/intro.md
└── assets/css/site.css
A template with settings carries them as YAML front matter between --- lines:
---
url: /
layout: default
---
{% extends "layouts/default.htm" %}
| Flag or field | Meaning |
|---|---|
--replace, Replace templates | Replace the templates and the config the theme already has; each replaced template keeps a revision. Without it, an existing template is skipped. |
code | The theme to import into; created from theme.yaml when it does not exist. |
Export and import from Rust
use lateritecmf::web::theme::archive;
let bytes = archive::export(&db, "acme").await?;
let report = archive::import(&db, "acme-copy", &bytes, false, Some(operator_id)).await?;
println!("{} written, {} skipped", report.imported, report.skipped);
ImportReport carries created, imported, skipped and ignored (files that are not templates).
Static Build
lat theme build writes a theme’s pages and text assets to a directory any static host serves.
lat theme build acme
lat theme build acme --out public --base-url https://acme.example
Every page whose URL has no parameter is written at its URL (/about to about/index.html), the /404 page also as 404.html, a page whose URL names a file (/robots.txt, /sitemap.xml) as that file, and the text assets under themes/<code>/assets/. A clean URL’s canonical link and this.url carry the trailing slash a static host serves it with (/about/). A page with parameters or a hidden page is skipped and named.
| Flag | Default | Meaning |
|---|---|---|
--out | dist | The output directory. |
--base-url | the application’s app.url, else one derived from server.listen | The origin url() and the canonical link use. |
--from <DIR> | the project’s theme.folder | Build a theme folder with no application; the folder’s name is the code. See Static Website. |
--copy <SRC>:<DEST> | the project’s theme.copy | A directory copied into the output at <DEST>. Repeatable. |
Preview a theme folder
lat theme serve
lat theme serve --from themes/acme --listen 127.0.0.1:3000 --copy docs/book:docs
| Flag | Default | Meaning |
|---|---|---|
--from <DIR> | the project’s theme.folder | The theme folder. |
--listen | the project’s server.listen, else 127.0.0.1:8080 | The address. |
--copy <SRC>:<DEST> | the project’s theme.copy | As build --copy. |
lat serve in a project with theme.folder is this preview.
Load a theme folder from Rust
use lateritecmf::web::theme::{build, folder};
let loaded = folder::load(Path::new("themes/acme")).await?;
let report = build::build(&loaded.db, &loaded.code, Path::new("dist"), "https://acme.example").await?;
| Field | Holds |
|---|---|
db | A private in-memory database holding the theme. |
code | The folder’s name. |
report | The ImportReport of the load. |
Build from Rust
use lateritecmf::web::theme::build;
let report = build::build(&db, "acme", Path::new("dist"), "https://acme.example").await?;
println!("{} pages, {} assets, {} skipped", report.pages.len(), report.assets.len(), report.skipped.len());
Build from the application
lat theme build renders without an application’s modules; a template that needs their markup or components is built from the application with build::build_with:
let report = build::build_with(
&db,
"acme",
Path::new("dist"),
"https://acme.example",
&[Arc::new(Money)],
&[&ComponentReg::new("acme.posts", "Posts", Arc::new(Posts))],
)
.await?;
| Argument | Meaning |
|---|---|
markup | The Markup registrations to install, in order. |
components | The ComponentReg registrations the pages attach. |
A site rendered by your own templating, with no theme, is covered under Static Site Generation.
Maintenance Mode
Maintenance mode answers every visitor with the theme’s /maintenance page, or a plain notice, until it is switched off.
use lateritecmf::web::theme::maintenance::MaintenanceSettings;
let settings: MaintenanceSettings = lateritecmf::admin::settings::load(&db).await?;
Settings › Website › Maintenance Mode, under web.manage_site:
| Field | Meaning |
|---|---|
| Show visitors the maintenance page | On, a visitor gets status 503 with Retry-After: 600. |
| Message | The plain notice’s text, when the theme has no page at /maintenance. |
| Page at | Serves |
|---|---|
/maintenance | Every visitor’s request while the mode is on. |
Keep working while it is on
A user with web.manage_themes sees the site as usual, with a bar at the foot of every page.
| Link on the bar | Opens |
|---|---|
| View as a visitor | The same path with ?maintenance=visitor: the maintenance page, status 503. |
| Turn it off | The Maintenance Mode settings screen. |
| Back to the site | The path without the query, from the visitor’s view. |
<div role="status" data-laterite-maintenance>...</div>
The bar sits before </body>, or at the end of a document without one.
Interactive Pages
A page posts to a component’s handler and swaps the answer into place; the component declares its handlers, the template attaches them.
use laterite_web::theme::component::{Component, ComponentContext, ComponentOutput, Handled, HandlerContext};
#[async_trait]
impl Component for Todo {
async fn run(&self, cx: &ComponentContext<'_>) -> Result<ComponentOutput, ThemeError> {
Ok(ComponentOutput::data(json!({ "items": load(cx.db).await? })))
}
fn handlers(&self) -> &'static [&'static str] {
&["add"]
}
async fn handle(&self, name: &str, cx: &HandlerContext<'_>) -> Result<Handled, ThemeError> {
let mut items = cx.input.list("items");
let item = cx.input.text("new_item").to_string();
if item.is_empty() {
return Ok(Handled::invalid("new_item", "Say what to add.").with_data(json!({ "items": items })));
}
if items.len() as u64 >= cx.property_u64("max", 10) {
return Ok(Handled::invalid("new_item", "The list is full."));
}
items.push(item);
Ok(Handled::data(json!({ "items": items })).inject("saved", true))
}
}
{{ framework() }}
<form {{ request('todo::add', target='#todo') }}>
{{ token('todo::add') }}
{% for item in todo.items %}<input type="hidden" name="items[]" value="{{ item }}">{% endfor %}
<input name="new_item">
<button>Add</button>
</form>
<div id="todo">{{ component('todo') }}</div>
{# partials/todo/default.htm #}
<ul>{% for item in component.items %}<li>{{ item }}</li>{% endfor %}</ul>
{% if errors.new_item %}<p class="error">{{ errors.new_item }}</p>{% endif %}
Declare a handler
| Method | Gives |
|---|---|
handlers() | The names a page may post to. A name not listed is a 404. |
handle(name, cx) | The outcome for one post, after run has produced the component’s data. |
cx.input.text(name) | The first value under name, trimmed; empty when absent. |
cx.input.list(name) | Every value under name or name[]. |
cx.input.has(name) | Whether the field was posted. |
cx.property_u64(name, default) | A number property of the attachment. |
cx.properties, cx.params, cx.path, cx.headers, cx.db, cx.preview | The request, as run sees it. |
Return an outcome
| Outcome | Renders |
|---|---|
Handled::data(value) | The alias with value as its data; .inject(name, value) adds a page variable. |
Handled::invalid(field, message) | Status 422 with errors.<field> in scope; .with_data(value) sets the alias’s data. |
.flash(level, text) on data or invalid | A message for the visitor: flash.level and flash.text in the page scope, and an out-of-band swap into <div id="flash"> for HTMX. |
Handled::Redirect(url) | HX-Redirect for HTMX, a 303 otherwise. |
Handled::Json(value) | The value as application/json. |
Handled::Unknown | A 404. |
Attach it in a template
| Function | Emits |
|---|---|
framework() | The script at /laterite/htmx.js, which also swaps a 422 into place. No inline script, so a script-src 'self' policy runs it. |
request(handler, target=, swap=, partial=, confirm=, indicator=) | hx-post to the page, hx-headers naming the handler and the partial, hx-vals with the visitor’s token, and the HTMX attributes given. |
token(handler) | The hidden _token and _handler fields, for a form that posts without a script. |
component(alias) | The alias’s markup: partials/<alias>/default.htm, else the component’s own. |
partial names a theme partial to render in place of the alias’s markup, with the page’s scope. Without HTMX the whole page renders, at 200 or 422, and a redirect is a 303.
Read the scope
| Name | Holds |
|---|---|
errors | The messages by field of a refused input; an empty map otherwise. |
laterite_token | The visitor’s token; request() and token() read it. |
this.url | The page’s URL, where the post goes. |
A post from another site, or without the visitor’s token, is a 403. The token is a cookie set on the first page and lives a day.
Show a flash
<div id="flash">{% if flash %}<p class="flash flash--{{ flash.level }}">{{ flash.text }}</p>{% endif %}</div>
Build it statically
A static build renders a page that attaches a component with handlers and warns, naming the page: a static host answers no post. Serve the site from the application, or keep such pages off a static host.
Colour Mode
A site offers light, dark, or follow the system, resolved before the first paint and kept in step with the system while the page is open.
<head>
{{ colour_mode() }}
<link rel="stylesheet" href="{{ asset('css/site.css') }}">
</head>
html[data-theme="dark"] { color-scheme: dark; background: #111; color: #eee; }
html[data-theme="light"] { color-scheme: light; background: #fff; color: #111; }
<button onclick="latSetMode('dark')">Dark</button>
<button onclick="latSetMode('light')">Light</button>
<button onclick="latSetMode('auto')">System</button>
| Function | Emits |
|---|---|
colour_mode() | The inline script, to place before any stylesheet. |
colour_mode(file=true) | A <script src="/laterite/theme-boot.js"> tag, for a Content Security Policy that forbids inline scripts; the site serves the file and a static build writes it. |
| Name | Holds |
|---|---|
<html data-theme="light"> | The resolved mode; write CSS against it. |
localStorage["lat-mode"] | The reader’s choice: light, dark or auto. |
latMode() | The current choice. |
latSetMode(mode) | Persists a choice and applies it. |
latApplyMode(mode) | Applies a mode without persisting it. |
Use it from Rust
use laterite_core::theme;
let head = format!("<head>{}<link rel=\"stylesheet\" href=\"/site.css\"></head>", theme::boot_markup());
| Name | Gives |
|---|---|
theme::boot_markup() | The inline <script> element. |
theme::BOOT_JS | The script alone, to serve as a file or embed with a nonce. |
theme::MODE_KEY | lat-mode. |
theme::MODES | ["light", "dark", "auto"]. |
A deferred or external script runs after the first paint, and a dark-mode reader sees the page flash white; the inline form avoids that.
Static Site Generation
laterite-web renders an application’s public pages to HTML at build time,
into a directory any static host serves.
[dependencies]
laterite-web = "0.12"
| Type | Role |
|---|---|
Meta | The shared <head> tags: title, description, canonical URL, Open Graph and Twitter card. |
StaticSite | Collects rendered pages, copies assets, and reports what it wrote. |
Templating is yours: any renderer that produces an HTML String.
Write a generator
use laterite_web::{Meta, StaticSite};
fn render_home(head: &str) -> String {
format!("<!doctype html><html><head>{head}</head><body><h1>Acme</h1></body></html>")
}
fn main() -> std::io::Result<()> {
let base_url = "https://acme.example";
let meta = Meta::new("Acme", "The Acme website.")
.canonical(format!("{base_url}/"))
.image(format!("{base_url}/static/card.png"));
let home = render_home(&meta.head_tags());
let mut site = StaticSite::new("dist", base_url)?;
site.page("/", &home)?;
site.assets("static", "static")?;
Ok(())
}
cargo run writes dist/.
Map URLs to files
Path passed to page | File written | Served as |
|---|---|---|
/ | dist/index.html | / |
/features/ | dist/features/index.html | /features/ |
/get-started | dist/get-started/index.html | /get-started/ |
Set page metadata
let meta = Meta::new(title, description)
.canonical(format!("{base_url}{path}"))
.image(format!("{base_url}/static/img/card.png"));
let head = meta.head_tags();
| Method | Description |
|---|---|
new(title, description) | Escaped; safe to build from content. |
canonical(url) | Also the Open Graph URL. Optional. |
image(url) | The social-share image. Optional. |
Publish extra files
let urls: Vec<String> = site
.paths()
.iter()
.map(|path| format!("{}{path}", site.base_url()))
.collect();
site.file("sitemap.xml", &your_sitemap(&urls))?;
site.file("robots.txt", "User-agent: *\nAllow: /\n")?;
| Method | Description |
|---|---|
paths() | Every page written, in order. |
base_url() | The prefix for absolute URLs. |
file(path, content) | Writes verbatim at the output root. Creates parent directories; refuses a path outside the output. |
assets(from, to) | Copies a directory recursively. |
No robots.txt or sitemap.xml is written for you.
Deploy
dist/ is plain files. On a host that builds from Git: build command
cargo run, publish directory dist.
A page whose content depends on the request (a form, a search, per-user
content, the admin) stays on the live server. A theme’s pages are built with
lat theme build.
Templating
A template extends a layout, fills its blocks, includes partials and content, and reads the theme global.
{% extends "layouts/default.htm" %}
{% block body %}
{% include "partials/nav.htm" %}
{{ partial("card.htm", title="Acme", body=page.body) }}
{{ content("intro.md") }}
<h1>{{ theme.name }}</h1>
{% endblock %}
Templates are named by the kind’s folder and the path:
| Kind | Name |
|---|---|
Kind::Layout | layouts/default.htm |
Kind::Page | pages/home.htm |
Kind::Partial | partials/nav.htm |
Kind::Asset | assets/css/site.css |
A theme’s own template is used, else the nearest ancestor’s.
| Name | Gives |
|---|---|
{% extends "layouts/<path>" %}, {% block %} | A page inside a layout (see Tags). |
{% include "partials/<path>" %} | A partial with the current variables. |
partial(<path>, name=value, ...), content(<path>, name=value, ...) | A partial or a content block (see Functions). |
theme | code, name, author, homepage, description of the theme rendered, and its settings (see Properties). |
Escape output
HTML is escaped in every template but an asset. A printed undefined value is an error; {% if page.sub %} on an undefined value is not.
Check a template
use lateritecmf::web::theme::{check, RenderError};
match check(source) {
Ok(()) => {}
Err(RenderError { line, message, .. }) => println!("line {line:?}: {message}"),
}
RenderError carries template, line, kind and message.
Render from Rust
use lateritecmf::web::theme::{Engine, EngineCache, Kind};
let engine = Engine::build(&db, "acme").await?;
let html = engine.render(Kind::Page, "home.htm", serde_json::json!({ "title": "Home" }))?;
let css = engine.render(Kind::Asset, "css/site.css", ())?;
// One engine per theme, rebuilt when the theme or an ancestor changes.
let cache = EngineCache::new();
let engine = cache.get(&db, "acme").await?;
cache.invalidate("acme");
// The application's own functions, filters and globals.
let engine = Engine::build_with(&db, "acme", |env| {
env.add_function("year", || 2026);
})
.await?;
Add markup from a module
use lateritecmf::web::theme::markup::{Markup, MarkupReg};
use minijinja::Environment;
use std::sync::Arc;
struct Money;
impl Markup for Money {
fn install(&self, env: &mut Environment<'static>) {
env.add_filter("money", |minor: i64| format!("{}.{:02}", minor / 100, minor % 100));
env.add_function("year", || 2026);
}
}
fn register(&self, registry: &mut Registry) {
registry.add(MarkupReg::new("acme.money", Arc::new(Money)));
}
{{ price|money }} in {{ year() }}
Every registration is installed in order. A static build takes the registrations through build::build_with.
Properties
Every page, layout and partial reads the request as this, the page’s head tags as head, and the theme as theme.
<html>
<head>{{ head }}</head>
<body>
<h1>{{ this.page.title }}</h1>
<p>{{ this.params.slug }} on {{ this.url }} in {{ this.theme.name }}</p>
{% if this.preview %}<p>Previewing.</p>{% endif %}
{% block page %}{% endblock %}
</body>
</html>
| Name | Gives |
|---|---|
this.page | The page’s settings and name (see Pages). |
this.params | The URL’s parameters. |
this.theme | code and name. |
this.layout | The layout the page named. |
this.url | The request path. |
this.preview | Whether an operator is previewing. |
head | The title, description, canonical, Open Graph and robots tags from the page’s settings; a setting may carry an expression. |
theme | code, name, author, homepage, description of the theme rendered. |
theme.<field> | A value of the theme’s own settings. |
Read a component’s data
<h1>{{ post.items[0].title }}</h1>
<footer>{{ site_name }}</footer>
| Name | Gives |
|---|---|
<alias> | The data a component attached under that alias returned. |
<name> | A value a component injected into the page scope. |
component | Inside a component’s markup, its own data. |
Tags
A tag is a {% %} statement: a page extends a layout, fills its blocks, includes a partial, loops and branches.
{% extends "layouts/default.htm" %}
{% block page %}
{% include "partials/nav.htm" %}
{% for item in latest.items %}<li>{{ item.title }}</li>{% endfor %}
{% if this.preview %}<p>Previewing.</p>{% endif %}
{% endblock %}
| Tag | Gives |
|---|---|
{% extends "layouts/<path>" %} | A page inside a layout. |
{% block <name> %}...{% endblock %} | A block the layout defines and the page fills; {% block page %} in a layout is where the page renders. |
{% include "partials/<path>" %} | A partial with the current variables. |
{% for item in items %}...{% endfor %} | One pass per item. |
{% if value %}...{% endif %} | A branch; an undefined value is false. |
Fill a layout from a page
{% block title %}{{ this.page.title }}{% endblock %}
<h1>{{ this.page.title }}</h1>
A page whose settings name a layout fills the layout’s page block, and a block the page defines at its top level fills the layout’s block of that name without rendering in place. A page that writes {% extends %} itself is left as written (see Layouts and Partials).
Filters
A filter follows a value after | and transforms it before it prints.
{{ post.body|content }}
{{ post.summary|markdown }}
<img src="{{ post.image|variant('card') }}">
{{ price|money }}
| Name | Gives |
|---|---|
<html>|content | Snippets in stored HTML expanded (see Snippets); content(<path>) does the same for a block. |
<text>|markdown | Markdown rendered to HTML: CommonMark with tables, strikethrough, footnotes, task lists and {#id} heading attributes; a heading without one gets an id from its text (## Release 0.9 is release-0-9); raw HTML passes through. |
<url>|variant("card") | A media URL rewritten to the named preset (see Image Variants). |
Add a filter from a module
impl Markup for Money {
fn install(&self, env: &mut Environment<'static>) {
env.add_filter("money", |minor: i64| format!("{}.{:02}", minor / 100, minor % 100));
}
}
The registration is described under Templating.
Functions
A function is called in {{ }} and gives a URL, a rendered partial, a content block or a component’s markup.
<a href="{{ page('blog/post', slug=post.slug) }}">{{ post.title }}</a>
{{ partial("card.htm", title="Acme", body=page.body) }}
{{ content("intro.md") }}
<link rel="stylesheet" href="{{ asset('css/site.css') }}">
<link rel="canonical" href="{{ url(this.url) }}">
<img src="{{ media(post.image, preset='card') }}">
{{ component('latest') }}
| Name | Gives |
|---|---|
page(<name>, param=value, ...) | The URL of the page named by its path without the extension; a parameter left out takes its default (see Pages). |
partial(<path>, name=value, ...) | A partial with the named variables, the request’s this and head, and the globals. |
content(<path>, name=value, ...) | A content block: .md rendered to HTML, .htm and .html as they are, anything else escaped as text; {name} in the block is the named variable, escaped (see Content). |
asset(<path>) | The URL of the theme’s text asset: /themes/<code>/assets/<path>. |
url(<path>) | The absolute URL of a path on the site, from the deployment’s origin. |
media(<file>), media(<file>, preset="card") | The URL of a media value (a URL, or an object with url as theme::media_value builds), under a preset when one is named. |
component(<alias>) | The theme’s partials/<alias>/default.htm, else the component’s own markup, with the data as component and under the alias, beside this and head (see Components). |
framework() | The request framework’s script and its island (see Interactive Pages). |
request(<handler>, target=, swap=, partial=, confirm=, indicator=) | The attributes that post a form or element to a component’s handler, with the visitor’s token. |
token(<handler>) | The hidden fields a form posts to a handler without a script. |
colour_mode(), colour_mode(file=true) | The colour mode script, inline or as a file (see Colour Mode). |
Add a function from a module
impl Markup for Money {
fn install(&self, env: &mut Environment<'static>) {
env.add_function("year", || 2026);
}
}
{{ year() }}
The registration is described under Templating. A static build sets the origin url() uses with --base-url.
Behaviours
What the admin does with no configuration, and the key that changes it.
Forms
| Where | Default | Change it |
|---|---|---|
| A single-line field | Enter submits the form. | enter: off on the form; enter: off or enter: next on a field. |
| A picker or a repeater row | Enter acts inside it. | data-lat-enter-scope and data-lat-enter-target on a widget of your own. |
| A field’s width | The whole row. | span: 1/2, 1/3, 2/3, 1/4, 3/4; break: true. |
| A repeater | Past 3 fields a row, rows collapse to the line naming them; fewer stay open. | display: list or inline. |
| A repeater row | Moves up and down, copies into a new row beneath it, and is removed. | reorder: false, duplicate: false. |
| A refused save | The form returns with its errors, values kept (a repeater’s rows and a checklist’s ticks included), and the cursor in the first field it refused. | focus: off. |
| A new record | Opens with the cursor in its first field. | focus: off. |
| Leaving with changes unsaved | Asks first, with the cursor on Stay. Typing and undoing it is not a change. | confirm_leave: false. |
| Save and continue editing | Offered beside Save on a resource with relations; the save lands on the edit page. A create page names the sections it will have. | Declare no relations. |
A field with a max_length rule | The control holds the limit, and a count appears once four fifths of it are used. | counter: true or false. |
| A textarea | As tall as its text, from rows up to most of the window. | grow: false. |
| A password field | A button shows what was typed. Sending the form hides it again. | reveal: false. |
A field with preset | Follows the named field as it is typed, until edited. | Omit the key. |
| A select past 10 choices | Searched: a box that filters the choices as you type. | search: true or false. |
A field with trigger | Shows, hides, enables, disables, empties or fills itself as the watched field changes. A hidden field is left out of the submission. | Omit the key. |
| A checklist past 10 choices | Offers select all and select none. | select_all: true or false. |
| A checklist past 20 choices | Offers a search box. | search: true or false. |
| A checklist past 10 choices, in groups | A group with every box ticked, or none, starts closed. A group partly ticked starts open. | expand: all or none. |
form:
enter: off
confirm_leave: false
fields:
sku: { enter: next, span: 1/3 }
links: { type: repeater, display: list, fields: { url: { input: url } } }
tags: { type: checklist, select_all: false, expand: all, options: [{ value: new }] }
Lists
| Where | Default | Change it |
|---|---|---|
| Search | Asks as you type. | search: { on_enter: true }; search: { enabled: false }. |
| Columns and page size | Each operator’s choice is remembered. | per_page sets the size; per_page_options offers a choice of sizes. |
| A column | Sortable, visible, read-only. | sortable: false, invisible: true, editable: true. |
| Export | Off. | exportable: true. |
| Deleting rows | Off. | deletable: true; it asks before it deletes. |
| Rows in an order of their own | Off. | reorder: true keeps the order in sort_order; reorder: { column: position } names the column. An integer column, not null, default 0. The list opens in that order with a grip to drag and Move up / Move down on every row; a sorted, searched or filtered view shows neither. A has-many section’s list takes the same key. |
| Rows as a tree | Off. | tree: true reads the parent from parent_id; tree: { parent_key: folder_id, source: acme.folders } names the column and a picker source. The list opens on the rows with no parent; a row with children expands in place, or opens them as a page with scripting off. With a source, every row offers “Move to”, which picks the new parent from it or leaves it empty for the top level, and a record never moves under itself. With reorder too, a move stays among one parent’s children. |
| A row | Opens its record on a click or Enter, when the list has a form. A modified or middle click opens a new tab. | row_click: none. |
| Returning to a list | The sort, search and filters used last come back, for the session. Clearing them forgets them. | remember: false. |
| A stored code in a column | Shown as stored. | labels: [{ value, label }] shows a label for each value. |
list:
search: { on_enter: true, prompt: Search posts }
per_page_options: [25, 50, 100]
exportable: true
reorder: { column: position }
tree: { source: acme.pages }
row_click: none
remember: false
columns:
title: { editable: true }
status: { labels: [{ value: pub, label: Published }, { value: dr, label: Draft }] }
Messages and dialogs
| Where | Default | Change it |
|---|---|---|
| A success or info message | Leaves after five seconds. | session.push_flash_sticky(..) keeps it until dismissed. |
A control with data-lat-confirm | Asks before it acts. | Omit the attribute. |
| A menu | Closes on a click outside, a chosen link, or Escape. | data-lat-keep-open. |
Tooltips
<button type="button" aria-label="Archive"
data-lat-tooltip="Archive"
data-lat-tooltip-position="top"
data-lat-tooltip-hotkey="Ctrl+E, Ctrl+Shift+E">…</button>
| Attribute | Values | Default |
|---|---|---|
data-lat-tooltip | The text to show. | No tooltip. |
data-lat-tooltip-position | top, bottom, left, right | bottom, or the opposite side when the chosen one has no room. |
data-lat-tooltip-hotkey | Shortcuts, comma separated, written with Ctrl, Alt, Shift. | None. A Mac shows ⌘, ⌥, ⇧. |
| Where | Default | Change it |
|---|---|---|
| A pointer resting on the element | Shows the tooltip after 300 ms. | Omit data-lat-tooltip. |
| Keyboard focus | Shows the tooltip at once. | Omit data-lat-tooltip. |
| Escape, a click, a scroll, a swap | Hides the tooltip. | None. |
| Touch | No tooltip; aria-label names an icon-only control. | None. |
lat.tooltip.show(document.querySelector('#archive'));
lat.tooltip.hide();
Accounts and sessions
| Where | Default | Change it |
|---|---|---|
| A new password | At least 8 characters. | [auth.password_policy] min_length. |
| A generated password | Temporary: every screen leads to Preferences until it is replaced. | lat admin create without --generate sets a password that is kept. |
| The top bar’s order | The registry’s order. An operator drags the tabs into their own, kept with their preferences. | “Reset the menu order” on Preferences. |
| Finding a page or a record | The search button or Ctrl+K opens the command palette over menu entries, settings and the records of resources with a palette source. | palette: <picker source> on a resource adds its records. |
| Failed sign-ins | 5 for a username from one address, 20 from one address, in 15 minutes. | [auth] max_failures, max_failures_per_address, failure_window_secs. |
| A session | Ends after 2 hours idle, or 12 hours. | [auth] session_idle_timeout_secs, session_absolute_timeout_secs. |
| Expired sessions | Removed hourly. | lat admin purge runs it on demand. |
[auth]
max_failures = 5
session_idle_timeout_secs = 7200
[auth.password_policy]
min_length = 12
Command Line
lat scaffolds, runs and maintains an application. Every command accepts
--database-url <URL>, falling back to DATABASE_URL, then to the
configuration of the application found from the current directory upward.
cargo install laterite-cli
lat --help
lat <command> --help
Scaffold
| Command | Description | Options | Example |
|---|---|---|---|
new [NAME] | Scaffold and set up a new application, or a static website (interactive). | --static: a static website. --content files|folder|git|database: where its content lives, default files. --plugin <SOURCE>: install a plugin, repeatable. --framework-path <PATH>: build against a local framework checkout, also read from LATERITE_FRAMEWORK_PATH. --url, --timezone, --listen, --admin <USERNAME> with --admin-email, --admin-name and the password in LAT_NEW_ADMIN_PASSWORD: answer the prompts up front. | lat new "Acme" --static --content git --url https://acme.example --timezone UTC --listen 127.0.0.1:8080 --admin admin --admin-email admin@acme.example --admin-name Ana |
make:migration <DESCRIPTION> | Scaffold a migration file in this crate’s src/migrations/. | --path <PATH>: the crate directory, default .. | lat make:migration create_articles |
make:plugin <ID> | Scaffold a plugin crate; <ID> is vendor.name. | --path <PATH>: where to create it, default .. --admin: scaffold the admin half. | lat make:plugin acme.blog --admin |
make:resource <NAME> | Scaffold an entity’s migration, schema, store and admin screen. | --path <PATH>: the crate, default .. --field <name:type>: columns beyond id and timestamps; types text, integer, boolean, datetime; repeat or comma-separate. --source <DIR>: keep the records as files in that folder, keyed by a slug column; `–format yaml | json |
make:model <NAME> | Scaffold a typed model struct for a table in src/models/. | --path <PATH>: the crate, default .. --field <name:type>: columns beyond id; types text, integer, boolean, datetime. --table <TABLE>: when it is not the plural. See Models. | lat make:model article --field title:text,views:integer |
seed [MODULE] | Run the application’s seeders, or one module’s. | --release; -p <PACKAGE>: the binary’s package in a workspace. See Seeding. | lat seed acme.blog |
Run and check
| Command | Description | Options | Example |
|---|---|---|---|
serve | Run this application, or preview a static website’s theme folder, optionally overriding the address. | --host <HOST>, --port <PORT>, --listen <HOST:PORT>, --release: build and run optimised. | lat serve --port 3000 |
doctor | Check that this application is set up to run, plugin dependencies included. | None. | lat doctor |
help-app | List the application’s commands, its modules’ included. | None. | lat help-app |
| any other | Run the application’s command of that name, added by a module (Console Commands). | The command’s own. | lat pdf check |
routes | List every URL the application answers: method, path, kind, owner, permission. | --path <TEXT>, --method <GET|POST|QUERY>, --kind <resource|screen|settings|public|page|framework>, --owner <MODULE>, --permission <CODE>, --public: keep matching rows, combined. --json: print JSON. --release. -p <PACKAGE>: the binary’s package in a workspace. | lat routes --path events --method POST |
Local domains
| Command | Description | Options | Example |
|---|---|---|---|
domain setup | Route *.<tld> to 127.0.0.1 via dnsmasq and a macOS resolver entry. | --tld <TLD>, default test. --dry-run. | lat domain setup --dry-run |
domain status | Report the current local-domain DNS state. | --tld <TLD>. | lat domain status |
domain teardown | Undo the wildcard DNS configuration. | --tld <TLD>. --dry-run. | lat domain teardown |
Admin users
| Command | Description | Options | Example |
|---|---|---|---|
admin create <USERNAME> | Create a superuser. | --email <EMAIL> and --first-name <NAME> required; --last-name <NAME>; --password <PASSWORD>, else prompted; --generate: print a strong random password. | lat admin create editor --email editor@acme.test --first-name Editor |
admin reset-password <USERNAME> | Set a new password for a user. | --password <PASSWORD>, else prompted; --generate. | lat admin reset-password editor --generate |
admin list | List the admin users. | None. | lat admin list |
admin unlock <USERNAME> | Clear a user’s failed-login lockout. | None. | lat admin unlock editor |
admin purge | Remove expired sessions and stay-signed-in credentials. | None. | lat admin purge |
Plugins
| Command | Description | Options | Example |
|---|---|---|---|
plugin add <SOURCE> | Add a plugin from a local path or a git URL, and record it. | --as <FOLDER>: the folder under plugins/, default the crate’s name. In a static website the first add writes its Cargo project and a plugin needs static = true. | lat plugin add ../blog-plugin |
plugin remove <NAME> | Remove a plugin from the list by crate name or folder. | --delete: also delete its folder. | lat plugin remove acme-blog --delete |
plugin sync | Regenerate the plugins-manifest crate from plugins/plugins.toml, then check the plugins’ dependencies. | None. | lat plugin sync |
plugin list | List the plugins this application compiles in. | None. | lat plugin list |
plugin check | Check each installed plugin against the expected layout and its dependencies, listing every crate built twice. | None. | lat plugin check |
Translations
| Command | Description | Options | Example |
|---|---|---|---|
i18n extract | Regenerate each crate’s lang/messages.pot from its source strings. | None. | lat i18n extract |
i18n check | Fail if any committed messages.pot is out of date. | None. | lat i18n check |
i18n update <LOCALE> | Merge each crate’s messages.pot into a locale’s .po, keeping existing translations; creates the .po if absent. | None. | lat i18n update fr |
i18n status | Report translation coverage for each crate’s locale catalogs. | None. | lat i18n status |
Themes
| Command | Description | Options | Example |
|---|---|---|---|
theme export <CODE> | Write a theme and its templates to a zip. | -o, --out <FILE>, default <code>.zip. | lat theme export acme -o acme.zip |
theme import <CODE> <FILE> | Create or update a theme from a zip. | --replace: replace templates and config the theme already has; each replaced template keeps a revision. | lat theme import acme acme.zip --replace |
theme list | List the themes. | None. | lat theme list |
theme build [CODE] | Render a theme’s fixed pages and assets to a directory, for a static host. | --from <DIR>: a theme folder instead of the database, default theme.folder. -o, --out <DIR>, default dist. --base-url <URL>, default app.url, else one derived from server.listen. --copy <SRC>:<DEST>: a directory copied into the output; repeatable, added to theme.copy. | lat theme build --copy docs/book:docs |
theme serve | Preview a theme folder, rebuilt on every change. | --from <DIR>, default theme.folder. --listen <HOST:PORT>, default server.listen. --copy <SRC>:<DEST>. | lat theme serve |
theme publish | Make the theme’s saved changes visible to the host: the source’s publish step, then theme.publish.hook. | None. | lat theme publish |
Media
| Command | Description | Options | Example |
|---|---|---|---|
media gc | Remove files outside the library that nothing links to, and the blobs no record names any more. | --grace <HOURS>: leave younger files alone, default 24. --dry-run. --storage <DIR>, default backend.storage. | lat media gc --dry-run |
media verify | Re-hash every stored file against its record. | --storage <DIR>, default backend.storage. | lat media verify |
Key
| Command | Does |
|---|---|
lat key generate | Writes a new application key as app.key in config/local.toml; --rotate keeps the old key under previous_keys, --print prints without writing. |
lat key show | The id of the key in use and of the previous keys. |
lat crypt rotate | Re-seals every sensitive column under the key in use, after lat key generate --rotate. |
Cache
| Command | Does |
|---|---|
lat cache clear | Moves every cache namespace on; every process reads afresh. --namespace records::posts moves one. |
lat cache list | Every namespace the deployment knows, with its generation. |
Queue
| Command | Does |
|---|---|
lat queue work | Runs the application’s worker (cargo run -- queue work); --once, --stop-when-empty, --queue high,default, --release. |
lat queue list | How many jobs wait and run on each queue. |
lat queue failed | The failed list. |
lat queue retry <id|all> | Puts a failed job back on its queue. |
lat queue forget <id|all> | Drops a failed job. |
lat queue flush [--queue name] | Drops every waiting job, or one queue’s. |
Schedule
| Command | Does |
|---|---|
lat schedule run | Runs the application’s ticker (cargo run -- schedule run); --once evaluates this minute and exits. |
lat schedule list | Every entry that has run on this deployment, with its last run. |
| Command | Does |
|---|---|
lat mail test <address> | Sends the built-in test template to the address through [mail]. |
API Reference
Every public type, function and trait carries doc comments.
cargo doc --workspace --no-deps --open
| Crate | Published |
|---|---|
lateritecmf | https://docs.rs/lateritecmf |
laterite-core | https://docs.rs/laterite-core |
laterite-auth | https://docs.rs/laterite-auth |
laterite-admin | https://docs.rs/laterite-admin |
laterite-media | https://docs.rs/laterite-media |
laterite-web | https://docs.rs/laterite-web |
laterite-cli | https://docs.rs/laterite-cli |
laterite-macros | https://docs.rs/laterite-macros |