Reference

Everything an app writes, in one place. For a walkthrough, see the tutorial (a server) or local-first. events.md covers models, history and undo.

The app#

src/main.rs names the backend with one app!:

src/main.rsBackendWhat it names
soda_server::app!(board::Board);Server, on events (the default)A soda::Model
soda_server::app!(board::Board per board);Server, on events, a model for each [board]A soda::Model
soda_server::app!(plain book::Book);Server, on its own stateA soda_server::App
soda_local::app!(model::Stock, …);Local-firstA soda_local::App, or a soda::Model that's LocalFirst
soda_static::app!(site::Site, url = "…");StaticA soda_static::App

app! writes the program: the router built from src/routes, the typed links (link::…), the app's prelude (crate::prelude::*, with its own Cx and Act), and main.

build.rs is soda_build::routes(), so Cargo rebuilds when a route is added or removed. The page shell is web/app.html; pages render between its <!--app--> and <!--/app-->.

On a server, on events#

app! names a soda::Model (events.md). Its events are stored in SQLite (data/events.db) or the Postgres that SODA_STORE names. app! also adds a test that the events' shapes only grow (events.lock).

soda::Model
type EventWhat's stored: Clone + Debug + PartialEq + Serialize + Deserialize + Shape + Send + Sync (#[derive(Shape)], #[shape(events)])
type CommandWhat actions ask for (Clone for cx.act on soda-server: a change another server got in ahead of is decided again)
type StepWhat one undo takes back (() for none)
fn decide(&self, by, now, command) -> Result<Vec<Event>, String>A command into events, or a refusal
fn evolve(&mut self, by, at, &Event)Applies one event
fn describe(&self, who, &Event) -> StringThe event in words, for the history
fn step(&self, by, &[Event]) -> Option<Step>What undo needs, read before the change
fn travel(&self, by, &Step, forward) -> Result<Vec<Event>, Stale>The events that undo (or redo) it, if it still applies
fn what(&Step) -> String, fn gone(&Step) -> StringUndo's words: "moving the card", and what to say when it's gone
fn touches(&self, &Event) -> TouchedWhat the event changed, for the pages listening for it: Touched::of([Topic::Card(id)]). Without it, Touched::All: every open page is drawn again
const HISTORY: usizeHow many of the latest changes the server keeps in memory, to look back on (default 1,000; 0 for none). Older ones stay in the store
fn save(&self) -> Option<Vec<u8>>, fn load(&[u8]) -> Option<Self>The model as a checkpoint, so a server starts from the latest rather than every event (soda::model::as_json, from_json). Without them, it folds them all
const RULES: u32Which rules a checkpoint was saved under: change it when evolve (or save) changes, and the next start folds every event again

A topic is a value of the app's own type, so a misspelled one doesn't compile: #[derive(Hash, soda::Topic)] enum Topic { Card(String), Column(Column) }. Strings are topics too.

app!(board::Board per board) keeps a model for each value of the [board] route param: its own stream (app:<board>), history, undo, who's here and open pages, read from the store when a page first opens it and let go ten minutes after its last page closes. Pages under [board] read and change that board. A change draws only its pages. A page outside one has an empty cx.app, can't act, and lists the boards with cx.spaces(). soda.js sends each /api/ request with the address of the page that sent it (Soda-At), so Soda's own routes (undo, history, names, presence) reach the right board. The pages' #app says its board (data-space). Without a [board] folder in src/routes (or with the param named otherwise), it doesn't compile.

Limits, on a server#

Either server form takes limits = …: what one person, or one network, can do at once, how many pages the server has room for, and what it sends in a day. None by default.

soda_server::app!(board::Board, limits = soda_server::Limits { actions: 20, network_actions: 200, pages: 20, ..soda_server::Limits::NONE });
Field
actionsActions a second from one session, on average; twice as many at once. Every post counts (the app's actions, undo, redo, a name) but a page moving
network_actionsThe same from one network, all its sessions together (a script without cookies is a new session each time)
pagesPages one session has open at once (each holds a stream)
network_pagesThe same for one network
roomPages open at once, everyone's together. Past it, a page waits in line, shown as it loaded under its place in line ("It's full right now. You're 37th in line…", Soda's status over the page), and nothing is drawn for it. It comes in as a page closes, first come first in. While others wait, a page whose person is away (its tab hidden a minute, or nothing heard from them for ten) gives up its place after its first minute in. The line holds five times the room
megabytes_a_dayWhat the server sends in a day (UTC), everything together, counted as it goes out. Past it, the server rests till midnight UTC: streams end, and anything asked for is answered 503, with Retry-After. The count is kept in the data folder, so a restart doesn't start it over. On a host that bills by what's sent (Fly.io), it caps the month's bill

Over a limit, an action is refused in words ("That's a lot at once. Try again in a moment."), as JSON with a 429 to X-Soda: json, and a page's stream answers 429 (it tries again, as after a restart). A network is an address, an IPv6 one's /64: on Fly.io the visitor's (Fly-Client-IP), otherwise whatever connected. Counted only for a limit that's set.

On a server, plain#

app!(plain …) names a soda_server::App: any Send + Sync type.

impl App for Book {
    async fn start() -> Result<Self, Box<dyn Error + Send + Sync>> {
        Ok(Book::open(&soda_server::data().join("book.db")).await?)
    }
    fn routes() -> Router<Arc<Self>> {
        Router::new().route("/health", get(|| async { "ok" })).route("/hook", post(hook))
    }
}

async fn hook(State(book): State<Arc<Book>>, pages: Pages) -> &'static str {
    book.sign(/* … */);
    pages.notify(["book"]); // or pages.changed(): every open page
    "ok"
}
  • start runs once. An Err stops the server and prints why.
  • routes (optional) adds axum routes beside the pages: webhooks, feeds, health checks. A handler that changes what pages show takes Pages. soda_server::axum is the axum it serves with.
  • soda_server::data() is the data folder, for the app's own database file.

Local-first#

soda_local::app!(model::Stock, catching_up = "Catching up on the pantry…");
Setting
catching_upWhat the page says while it syncs changes made while it was away
cspThe page's own Content-Security-Policy (the engine adds each page's nonce, which Datastar's expressions run by, to its script-src)
bar = falseThe root layout places Soda's bar itself, in parts (cx.bar(…)), with cx.notices()

The model is a soda_local::App, or any soda::Model that implements soda_local::LocalFirst (the same model a server runs, events.md).

Static#

soda_static::app!(site::Site, url = "https://atlas.example");

app! names a soda_static::App: any Send + Sync type with async fn load() -> Result<Self, Box<dyn Error + Send + Sync>> (read from the site's folder) and an optional const WATCH: &[&str] (the folders soda dev watches; none by default). See static.md.

  • With --build <dist>, the program renders every page into dist/. Without it, it serves them.
  • url is where the site is served. With it, each page gets <link rel="canonical"> and og:url (where the shell has those tags), and the build writes sitemap.xml.
  • No actions: an #[action] is a compile error. A download is built once, and takes only cx.

Environment#

VariableDefault
SODA_ADDR127.0.0.1:3000Where a server (or an unbuilt static site) listens
SODA_DISTdistThe built site it serves
SODA_DATAdata/The data folder: the event store, the session key, the app's own files
SODA_STOREdata/events.dbpostgres://… to keep the events in Postgres: any number of servers then share them, and the session key, who's here and the day's bytes (docs/events.md)
SODA_SECRETdata/session.key, or the Postgres store'sThe key sessions are signed with: the same on every server of an app (on Postgres, kept there without it)
SODA_STORE_URLThe app's own, at /_storeAnother store for a local-first build (soda dev and soda test set their own)
DATABASE_URLSet by soda deploy (Neon)A local-first app's store's Postgres, in its Vercel project
TURNSTILE_SECRETNone: no browser checkCloudflare's secret: new sessions must pass the browser check first
SODA_SDKThe SDK commit Cargo.lock pinsA local SDK checkout to build against, for working on both

Routes#

A folder under src/routes is an address.

FolderAddressParams field
src/routes//
shelves//shelves
shelves/[shelf]//shelves/riceshelf: String
docs/[[page]]//docs, /docs/intropage: Option<String>
files/[...path]//files/a/bpath: Vec<String>
(admin)/settings//settings (a group, not in the address)
FileDefines
page.rspub fn page(cx: &Cx<Params>) -> View (or Result<View>); optional pub fn head(cx) -> Head; on a static site with params, pub fn params(cx: &Cx) -> Vec<Params> (the pages to build)
layout.rspub fn layout(cx: &Cx<Params>, children: View) -> View, around every page below it. Local-first, the root's also has pub fn intro() -> View, the start screen's words (slot="header" goes across its top, slot="aside" beside its forms)
actions.rs#[action]s, what its forms and buttons post to
downloads.rs#[download]s
not_found.rsThe page for a missing thing below it (.ok_or(NotFound)?, an unknown address): a 404 on a server
error.rsThe page for any other error below it: a 500 on a server
  • head: Head::title("…").description("…"). Whenever a page renders whole (a server's first response, a static build), the title goes in <title> after the app's name and in og:title; the description in <meta name="description"> and og:description. Each is written only where the shell (web/app.html) has the tag.
  • Structured data: soda::view::structured_data(&json!({…})) in a view writes schema.org JSON-LD (the business, the person, the article) for search engines and assistants; it's the only script a view can hold.
  • Async: on a server or a static site, a page, layout, head or download can be async fn.
  • Modules: a folder's files are its module (routes::shelves::shelf::actions), and its params are super::Params. A missing page or a param named twice is a compile error naming the file.
  • Links are typed functions of the params: link::root(), link::shelves::shelf(&id). Add a query with .with("q", "rice").
  • Path or query: a path is a place, with its own title and history entry. The query refines it in place (a filter, a search, a sort) or holds a dialog over it (?edit=…). Views that share a frame are pages in a group with a layout: (stock)/page.rs, (stock)/soon/page.rs, (stock)/layout.rs.

Local-first only#

  • #[prerender] pub fn page(cx: &Public) -> View: a page that needs no space (privacy, a landing page). It's rendered as HTML at build time, so it reads before anything runs. Public reads only the address; no params.
  • The space is in the address before the path: /~3fa9c2e1b0/shelves/rice. Routes, cx.page and links never see it; href, cx.go, Redirect, downloads and soda.go stay in the page's space. An address without one opens the last space; /~new/ is the start screen. A route folder can't start with ~.

Cx: what a page reads#

On a server, on events:

cx.appThe model: now, or at the point in history the page is looking at
cx.meThe viewer: id, name, hue, can_edit (false while looking back)
cx.here()Who has the app open (with per, this board), in arrival order, with what they're doing (focus); on several servers, each other server's first 50
cx.here_count()How many have it open, on every server
cx.spaces()With per: each board with something kept in it (id, changed), the latest changed first. The page is drawn again as they change, at most once a second
cx.history()Every change in words, for <History>
cx.looking_back(), cx.looking_at()How many changes back the page is, and that moment's time
cx.undo(), cx.redo()What this person's Undo / Redo would do, or None
cx.name_of(id)A person's current name
cx.timeline()Every change, as a soda::timeline::Timeline
cx.kept_in()Where events are stored ("SQLite, data/events.db")
cx.session()The browser's session
cx.listen(Topic::Card(id))Draw this page again only for changes that touch it (Model::touches), and its own session's. Without it, every change does
cx.listen_softly(Topic::Tally)Draw this page again for changes that touch it at most once a second (a count every change touches), at once if something it listens for changed too

On a server, plain:

cx.stateThe app's state (the App that app! names)
cx.sessionThe browser's session: its random id, and what it remembers, in a signed cookie that survives restarts
cx.listen("book")Re-render this page only after actions that notify("book"). Without it, every action re-renders it. A topic is a string or a value of the app's own #[derive(Hash, soda::Topic)] type
cx.listen_softly("count")Re-render it after actions that notify("count") at most once a second

Local-first:

cx.appThe open space's state
cx.spaceThe space: name, members, creator
cx.meThe viewer: id, name, can_edit (show controls only when true), owner
cx.bar("status people")Parts of Soda's bar, in order, for a layout that places it: spaces, name, people, status, undo, share, security
cx.sheet()Which of Soda's sheets is open (Some(Sheet::Share))
cx.notices()The space's and device's notices (an invite, a removal, a refused change, a wrong clock), for a layout without the bar. cx.passkey_nudge() is the passkey suggestion
cx.name_of(id)A member's name
cx.history(), cx.looking_back()The space's history, for <History>
cx.engine, cx.recThe engine's state and the space's record, for anything else (soda_local::ui::rev(cx.rec, target))

On every backend:

cx.paramsThe route's params
cx.pageThe address, with its query
cx.query("q")One query value. Anyone can write a link, so validate it
cx.query_as::<T>()The whole query, into a type whose fields are all optional
cx.here_with(&[("edit", Some(id))])This page with its query changed (None removes a key)
cx.link(href), cx.link_within(href)A link that knows if it's the current page (or, within, the page or below it), for <Tab> and <MenuItem>
cx.choice("show", &["todo", "done"])A filter in the query: .value(), .is(Some("done")), .link(option)
cx.filters(&["who", "q"])The page's filters: .get("who"), .any(), .cleared(). Remembered per device (local-first) or per session (on a server)
cx.as_left(href)A link to a page with the filters it last had on this device (for a rail)
cx.recall("key")What an action stored with cx.remember (per device local-first, per session on a server)
cx.now(), cx.today()The time (ms) and the day (UTC), by this device's clock. A page that reads them re-renders each minute

Everyone: a page drawn once for everyone at its address#

On a server, a page that shows everyone at its address the same takes cx: &Everyone<Params> in place of &Cx<Params> (pub fn page(cx: &Everyone<Params>) -> View, async or not). The server draws it once a change for each address, and every page open there shows that drawing.

cx.app, cx.here(), cx.history(), cx.spaces(), cx.name_of(id), cx.timeline()As on Cx, on events (cx.state on app!(plain …))
cx.listen(topic), cx.listen_softly(topic)As on Cx: the shared drawing is drawn again for changes that touch it
cx.params, cx.page, cx.query(…), cx.query_as(), cx.here_with(…), cx.link(…), cx.link_within(…), cx.choice(…)As on Cx
cx.now(), cx.today()The server's clock. A page that reads them is drawn again each minute
cx.looking_back(), cx.looking_at()As on Cx: never, in the drawing everyone shares; someone looking back at the history has the page drawn for them alone, where it's theirs
<Mine with=you />What's each person's own: fn you(cx: &Cx) -> View is drawn for each of them (their cx.me, their cx.undo()), in its place in the drawing they share
data-person=idOn what's someone's (a roundel, a tag): soda.js marks it data-you on that person's page (#app has their id, data-me), for data-you:ring-accent or data-you:hidden

Not on Everyone, so a page that reads them doesn't compile: cx.me, cx.session, cx.undo(), cx.redo(), cx.filters, cx.as_left and cx.recall. A layout can take &Everyone too: those on &Everyone right around a page on Everyone (no layout on &Cx between them) are drawn into the drawing everyone shares, and a layout on &Cx, and a head, are drawn for each person around it. On the local engine or a static site, &Everyone is a compile error saying to take &Cx.

view!#

view! {
    <li class="thing flex gap-3" class:opacity-60=item.done id=format!("thing-{}", item.id)>
        <a href=link::shelves::shelf(&item.shelf)>{&item.name}</a>
        {item.use_by.map(|day| view! { <Date {day} /> })}
        {cx.me.can_edit.then(|| view! { <Button quiet on:click=UseUp(item.id.clone())>"Used up"</Button> })}
    </li>
}
Syntax
"text"Text, always escaped. An element whose whole content is data gets dir="auto"
{expr}Text, a number, a View, an Option of one, or an iterator of them
name=valueText, a number, a bool (present or not; aria-* writes "true"/"false"), or an Option. Wrap values containing < or > in (…): hidden=(n > 0)
href=…An Href, a download (href=StockList), or text
class="…"Literal classes, so Tailwind finds them
class:name=condAdds a class when true (any class: class:bg-accent/10=selected)
class=exprAdds a Class, text or an Option. All classes merge with cn; later ones win
on:event=Action(…)Posts to an action
on:event="…"A Datastar expression. Other Datastar attributes take only literal text; build one in code with Handler::raw(…)
bind:nameBinds a signal
show="$open"Shows or hides
query:nameMakes a field's value the query: <input type="search" query:q value=f.get("q")>. Typing updates the address in place; a <select> adds a history step
<form action=AddShelf>Posts the form to an action
<ItemRow {cx} {item} compact />A component. {item} is item=item; bare compact is compact=true

Errors point at the attribute and say what to write instead.

Components#

#[component]
pub fn ItemRow(cx: &Cx, item: &Item, compact: bool, class: Class, attrs: Attrs, children: View) -> View {
    view! { <li class="flex gap-3 py-3" class:py-1=compact class=class {attrs}>{&item.name}{children}</li> }
}
  • A cx: &Cx prop is the page it's rendered in, whatever that page's params. A component reads the page (cx.app, cx.me, cx.link(…)), never its route's params.
  • Props are required, except bool (false), Option, class: Class, attrs: Attrs, children: View, and #[prop(default)] / #[prop(default = …)]. A missing prop is a compile error naming it.
  • String props take anything that converts; #[prop(into)] does that for any type.
  • Attributes with - or : in the name (aria-label, on:click, data-x) go to attrs, written with {attrs}. attr:name=… sends any other attribute there.

The SDK's components#

Each uses Soda's own classes on the app's tokens (styling.md). A class passed in wins over its own.

ComponentPropsRenders
Buttonprimary, quiet, danger, small, submit, cancel (closes its edit-in-place or dialog), disabled<button class="soda-btn …">
Inputname, kind (its type), value, placeholder, required, autofocus, maxlength, autocomplete<input class="soda-input">
Textareaname, value, placeholder, rows (4), required, autofocus, maxlength<textarea class="soda-input">
Selectname, required; <option>s inside<select class="soda-input">
Fieldlabel, name, hint; a control insideLabel, control, hint, and the action's error for it
Card, ChipA bordered surface; a small rounded label
Timeat (ms), format (When::Ago, Short, Clock, Minute, Date, Full, Stamp)A moment in the reader's language and time zone
DatedayA calendar day in the reader's language
Clocksince, untilElapsed time, ticking
Countdownfrom, due, met, until, compact; fallback text insideA ticking deadline; :state(soon | overdue | met | late) for styling
Tabs, Tablabel, pills; a tab's href (a Link or Href) and currentLinks between views, the current one aria-current="page"
Dialogheading, open, close (the page without it), modal, lockedA dialog open while the address says so; Escape, ✕, a click outside, <Button cancel>, its form submitting and Back close it
Menu, MenuItemid, label, button (its face), button_class; an item's href or on:click, and currentA popover menu that closes on a choice
EditInPlacecurrent-<field>=… fills a field as it opensA <details> whose summary opens the form inside
Lists, List, ListItemmoves (an action taking Moved), disabled; a list's id, label, head, foot, items_class; an item's id, labelDrag between lists, or Alt + arrows
Historystops (cx.history()), at (cx.looking_back())The history line to scrub back along
Emptytitle; what goes here and the one thing to do, insideAn empty state
Avatarname, accountInitials in the person's own color

Browser packages#

Install a package from npm, and wrap it in a tag with wrap, in a file in web/components/:

npm i chart.js
// web/components/sales-chart.js
import { Chart, BarController, BarElement, CategoryScale, LinearScale } from 'chart.js'
import { wrap } from '/soda-component.js'

Chart.register(BarController, BarElement, CategoryScale, LinearScale)

wrap('sales-chart', {
  draw: (el, { chart }) => new Chart(el.appendChild(document.createElement('canvas')), chart),
  update: (instance, { chart }) => { instance.data = chart.data; instance.update() },
  remove: (instance) => instance.destroy(),
})
view! { <sales-chart class="h-64" data-chart=chart_json></sales-chart> }
wrap(name, …)
draw(el, attrs)Draws into el, an element inside the tag. Returns what update and remove need
update(instance, attrs, el)The tag's attributes again, each time the page's next drawing changes them. Without it, the tag is drawn afresh
remove(instance)The tag left the page
attrsThe tag's attributes, named without data-, in camelCase. JSON ({…}, […]) is parsed; the rest is text. Not class, style or id
  • The page's updates keep what the library drew, and keep the tag's attributes the server's. Soda's copy of Datastar does this for any element whose class has static drawsItself = true, which wrap sets (a hand-written class can too). Datastar's own data-ignore-morph also keeps the drawing, but its attributes then stop updating.
  • Every file in web/components/ loads itself: nothing imports it. Every build bundles them and web/kit.js, with the packages and files they import, into the site's /kit.js. soda dev bundles again when you save, or when package.json changes.
  • A package's CSS (import 'x/style.css') is bundled too, with its fonts and pictures. The app's utilities win over it, and the token check doesn't read it.
  • Another web/ file that imports a package by name fails the build: it isn't bundled. Imports by URL (/soda-component.js) stay as they are.
  • Deploys run npm ci --omit=dev, so packages belong in dependencies (where npm i puts them).
  • A build ships only what you use of each package: import the parts you need (import { Chart, BarController } from 'chart.js', not 'chart.js/auto').
  • A build prints the bundle's size and what's taking the room, names any CommonJS package (all of it ships), and warns past 250 KB compressed. License notices go to /kit.js.LEGAL.txt.
  • npm is for browser code only. Rust uses Cargo.

Actions#

// src/routes/shelves/[shelf]/actions.rs
use super::Params;
use crate::prelude::*;

#[derive(Form)]
pub struct ShelfName {
    #[form(max = MAX_NAME)]
    pub name: String,
    pub rev: Option<u64>,
}

#[action]
pub async fn rename(cx: &mut Act<Params>, form: ShelfName) -> Result {
    let command = PantryCommand::RenameShelf { id: cx.params.shelf.clone(), name: form.name };
    match form.rev {
        Some(rev) => cx.act_seen(command, rev).await?,
        None => cx.act(command).await?,
    }
    Ok(())
}
  • #[action] makes a CamelCase value (Rename, AddItem(shelf.id.clone())) for <form action=…> and on:click=…. Its URL comes from its route, so you never write one.
  • An argument named form is read from the posted form. Other arguments are passed in the view, owned (String, not &str). A Moved argument comes from <Lists>.

On a server, on events:

cx: &mut Act<Params>
cx.act(command).await?The model decides it; the events are stored and every open page re-renders. A refusal is the Err
cx.app()The model now
cx.me, cx.name_of(id)Who posted; anyone's name
cx.say_with_undo("Deleted “Fix login”.")A toast with an Undo button

Soda's own endpoints, posted by its components and keys: /api/undo and /api/redo (⌘Z, ⇧⌘Z), /api/scrub (<History>: { at } or { live: true }), /api/me ({ name }), /api/focus ({ on, doing }).

On a server, plain:

cx: &mut Act<Params>
cx.stateThe app's state, changed however the app keeps it
cx.sessionThe session that posted
cx.notify("book")Re-render pages that listen("book"), pages that never call listen, and this session's own. Without it, every open page re-renders

Local-first:

cx: &mut Act<Params>
cx.act(command).await?The model decides it; the events are signed, encrypted and synced. A refusal is the Err
cx.act_seen(command, rev).await?The same, checked against what the form showed: a change made meanwhile wins, and its author is asked
cx.read(|state| …)Reads the engine's state
cx.say_with_undo("Gave the 8 AM metformin.")A toast with Undo, while it's this device's to undo

On every backend:

cx: &mut Act<Params>
cx.say("…")A toast on this person's pages
cx.remember("key", value), cx.forget("key")Stores a value for cx.recall (per device, encrypted, local-first; per session on a server)
cx.go(link)Navigates the posting page when done
cx.keep(&["field"])Keeps these fields when the form resets
cx.keep_form()Keeps the whole form (and an open dialog)
cx.clear(&["signal"])Empties bound signals
cx.paramsThe route's params

More ways to post:

  • CheckIn.url() is an action's URL, for an element that posts itself: <ir-checkin action=CheckIn.url()>.
  • PostMessage.with_signals(&["message"]) posts bound signals as form fields; clear them with cx.clear(&["message"]).
  • A control that submits as it changes is a one-field form: <form action=Assign(id) class="contents"><select name="role" on:change="el.form.requestSubmit()">…</select></form>, with cx.keep_form() in the action.
  • A Handler prop takes an action as on: does: <Said ack=Acknowledge(id) />.
  • Local-first: on:click=Sheet::Share (or Sheet::Security) opens Soda's sheet (?sheet=share, closed by Back); Switch::To(id) / Switch::New opens another space, or the start screen; href=cx.space_link(&id) links to one.

An action returns Result. Each error shows where it belongs:

Return
Ok(())Done; pages re-render
Err(NotFound.into())The not-found page
Err("…".into())A refusal, shown as a toast (the engine's refusals too)
Err(FieldErrors::one("date", "That's in the past.").into())An error under its field
Err(Redirect::to(link).into())The posting page navigates there

A page that has moved returns Err(Redirect::to(link::…).into()). It navigates in place, leaving the old address out of history. A moved download redirects too.

Forms#

#[derive(Form)] reads a struct from the posted form. Each field's error shows under it (in its <Field>, or the browser's own bubble).

TypeReadsWhen empty
StringText, trimmed"Required."
Option<String>Text, trimmedNone
boolA checkboxfalse
numbers, Option<…>A number"Required." / None
Day, Option<Day>A date (2026-10-20)"Pick a date." / None
Vec<String>Every value of a name (checkboxes, a multiple select)[]
any FromStr, with #[form(parse)]Its own way"Required."
Attribute
#[form(max = 80)], #[form(min = 1)]Length or value limits
#[form(name = "how-many")]The posted field name
#[form(trim = false)]Keep whitespace
#[form(message = "…")]Replaces the rule's own error message

Downloads#

// src/routes/downloads.rs
#[download]
pub fn stock_list(cx: &Cx) -> Result<Download> {
    Ok(Download::text("pantry.txt", "text/plain", "…"))
}
// <a href=StockList download>"Download the list"</a>
  • Built when requested, from what the page reads: on the device (local-first) or on the server (where it can be async fn). Static sites build it once.
  • Served under /api/_ at its route's address. Arguments passed in the view (href=Receipt(order.id.clone())) go in its query.
Constructor
Download::text(name, mime, text)A text file
Download::new(name, mime, bytes)Any file
Download::page(name, html)A whole page shown in place, to read or print (<a href=PrintList target="_blank">): inline styles, and at most a button's onclick="print()"

Days#

Day (in the prelude) is a calendar day, written 2026-10-20 in forms, JSON and history.

"2026-10-20".parse()From text
Day::new(2026, 10, 20)From parts (None if it isn't a date)
Day::of(ms)The UTC day of a moment
day.until(other)Days between
day.plus(n)n days later
day.start(), day.end()Its first and last ms (UTC)

The CLI#

Command
soda new <dir> ["<Name>"]A server app on events, from templates/server (a Kanban board). The name defaults to the folder's, in words (family-pantry is Family Pantry)
soda new --plain <dir>A server app on its own state, from templates/server-plain (a checklist in SQLite)
soda new --local <dir> [--noun trip] [--plural …]Local-first, from templates/local: the same board on the same model. --noun names a space (default "board"); --plural fixes an irregular plural
soda new --local --plain <dir> [--noun pantry]A local-first checklist, from templates/local-plain (default noun "list")
soda new --static <dir>A static site, from templates/static: a home page, a guide and notes from Markdown
soda dev [--port 5180] [--no-hot]Serves the app, patching each change into it (hot-patching.md). --no-hot rebuilds and reloads instead
soda checkTests (with events.lock), Clippy, and the design-token check
soda testcheck, then the build and the end-to-end tests in real browsers
soda buildThe site in dist/, with a server's program beside it (a static site: every page)
soda deployShips it (below)
soda eventsA server app on events: where they're stored, how many, their shapes against events.lock, the latest
soda load [--viewers 100] [--for 10s] [--actions 5] [--arrivals 0] [--moves 0 --move '/?x={0..100}'] [--at /] [--action 'PATH BODY'] [--plain]A server app under many people at once, without browsers: its release build on a fresh data folder, N open pages, and a mix of its own forms' actions (or --actions), arrivals and moves. {a..b} in --at gives each page the next number in turn (--at '/b/{0..100}': a thousand pages, ten to a board), and elsewhere a number drawn each time. Its streams are compressed as Chrome takes them (zstd) and decoded as they come, unless --plain. Says what each change woke and drew, how long drawings took by route, the bytes drawn and on the wire, the server's CPU, how the actions and moves were answered, and what to reach for
soda load --site https://… [the same]The same mix on a site that's running, from here (no app folder needed): what its streams sent, on the wire, and how its actions and moves were answered (taken, over its limits, failed; how long). Its limits on one network hold for everything sent from one machine
soda events …
log [--last N] [--stream app|app:ID|people]Every change, oldest first (app: the model's, every board's with per; app:ID: one board's)
export [--to file]Every event as a CloudEvent, one JSON object a line
reset [--yes]Deletes a dev store (data/events.db, SQLite only)

soda deploy:

Backend
Local-first, staticA production build, published with Vercel
ServerA container image of the program and its site, serving on 8080, its data folder a volume
--image name:tagThe image's name (default: the app's, :latest)
--platform linux/amd64The platform to build for
--pushPushes the image to its registry
--to ssh://you@hostRuns it on that Docker host, replacing the last deploy and keeping its data
--publish 80With --to: the host's port
--fly [--region iad]To Fly.io: staged as for an image, built by Fly's builder, on one machine (its open pages are in its memory) with its data in a volume. The first time (no fly.toml), --region says where: it writes fly.toml (always on, stopped with SIGINT so it saves a checkpoint, HTTPS only, room for 10,000 connections) and makes the app, its volume and its addresses

This page is docs/reference.md in the SDK, built into this site as it is.

Esc