How Soda works

Soda has three layers:

  • The framework (soda, in kit/): routes, view!, components, actions, forms and typed links.
  • A backend: where the app runs. soda-server (server/), soda-local (the repository's root) or soda-static (static/).
  • The CLI (soda, in cli/): new, dev, check, test, build, deploy, events.

An app is written against the framework. Its backend decides what a page reads and what an action can change.

Maintainers: the decisions, milestones and measurements behind this are in design-notes.md.

The idea#

A page is a function of what it reads and its address. An action changes something, and every open page re-renders. That removes most of what makes Next.js and SvelteKit complicated: loaders, caching, revalidation, loading states, and the line between server and client components.

Next.js / SvelteKitSoda
app/blog/[slug]/page.tsx, +page.sveltesrc/routes/blog/[slug]/page.rs
layout.tsx, +layout.sveltelayout.rs, nested the same way
not-found.tsx, error.tsx, +error.sveltenot_found.rs, error.rs
(group), [...rest], [[optional]] foldersThe same
Server actions, form actions#[action] functions beside the page
<Link href>, goto()<a href=link::…> (typed); cx.go(…) in an action
generateMetadata, <svelte:head>pub fn head(cx) -> Head
Loaders, fetch, revalidatePath, suspenseNothing: a page reads what it needs as it renders
useState, $stateDatastar signals (bind:, show=)
Client components, islandsWeb components on the app's own utilities
cn() with tailwind-mergecn, read off the app's compiled stylesheet
Fast Refresh, HMRsoda dev: Rust patched into the running app in about a second
API routes#[download]s, and on app!(plain …) the app's own routes (App::routes)

An app's files#

pantry/
  Cargo.toml
  build.rs                   fn main() { soda_build::routes(); }
  events.lock                the events' shapes
  src/
    main.rs                  mod components; mod model; soda_local::app!(…)
    model.rs                 the model
    components.rs            shared components
    routes/
      layout.rs              wraps every page
      page.rs                /
      not_found.rs
      shelves/
        page.rs              /shelves
        [shelf]/
          layout.rs          wraps every page under /shelves/:shelf
          page.rs            /shelves/:shelf
          actions.rs         what that page's forms post to
      (account)/
        settings/page.rs     /settings
  web/
    app.html                 the shell
    app.css                  the design tokens
    components/expiry.js     a browser component (loads itself)
    kit.js                   any other browser code
  tests/e2e.mjs

src/main.rs declares the app's modules and calls the backend's app! macro, naming the model or state. The macro writes the rest of the program, main included:

mod components;
mod model;

soda_local::app!(model::Stock, catching_up = "Catching up on the pantry…");

Routes#

FileWhat it is
page.rsThe page: pub fn page(cx) -> View (or Result<View>), and an optional head
layout.rspub fn layout(cx, children: View) -> View, around every page at and under its folder
actions.rsActions for the pages in its folder (an #[action] in any of the folder's files counts)
not_found.rsShown when nothing matches, or a page returns NotFound
error.rsShown when a page returns another error
downloads.rs#[download]s: pub fn name(cx) -> Result<Download>
FolderMatches
shelves/shelves
[shelf]One segment, as shelf: String
[...path]One or more segments, as path: Vec<String>
[[lang]]An optional segment, as lang: Option<String>
(group)Nothing: groups routes under a shared layout without adding to the URL
// src/routes/shelves/[shelf]/page.rs
use super::Params;
use super::actions::AddItem;
use crate::prelude::*;

pub fn head(cx: &Cx<Params>) -> Head {
    Head::title(cx.app.shelf(&cx.params.shelf).map_or("Shelf", |s| s.name.as_str()))
}

pub fn page(cx: &Cx<Params>) -> Result<View> {
    let shelf = cx.app.shelf(&cx.params.shelf).ok_or(NotFound)?;
    Ok(view! {
        <h1 class="font-display text-3xl">{&shelf.name}</h1>
        <form action=AddItem class="flex gap-2">
            <Input name="name" required />
            <Button primary submit>"Add"</Button>
        </form>
    })
}
  • Cx is what a page reads: cx.params, cx.page (the address and query), and what its backend adds (see Backends). cx.query("tab") reads the query, cx.here_with(…) links to this page with its query changed.
  • Each folder has a generated Params, which its files read as super::Params. Params are text. A page that wants another type parses it and returns NotFound when it can't.
  • NotFound renders the nearest not_found.rs. Any other error renders the nearest error.rs.
  • Layouts nest from the root down. A layout is left alone when you move between the pages under it, so its open menus, scroll and focus stay.

Every page gets a link function, taking its params:

link::root()                                        // "/"
link::shelves::shelf(&id)                           // "/shelves/rice"
link::shelves::shelf(&id).with("tab", "history")    // "/shelves/rice?tab=history"

A link to a page that doesn't exist, or with the wrong params, doesn't compile. Rename a folder and the compiler lists every link to fix.

How the router is built#

Rust can't read a folder at run time, so the compiler does. The backend's app! expands to soda::__routes!, a procedural macro that reads src/routes/ on every compile (hot patches included) and writes:

  • a module per folder ([shelf] is shelf, (account) is account), with its ROUTE, its Params and its files;
  • the matcher, most specific route first, rendering each page inside its layouts;
  • the action dispatcher and the link:: functions;
  • the app's Cx, Act and prelude, over its backend.

A route the router can't make sense of is a compile error naming the folder: two pages for one address, two folders that would be one module, a page.rs without page. The rest of the router is still written, so the app compiles around it. build.rs (soda_build::routes()) tells Cargo to compile again when a folder is added. rust-analyzer expands the macro, so completion works on routes and links.

Moving between pages#

soda.js intercepts links to the same site and asks the backend for the new page, which arrives over the page's stream and is morphed in. Back and Forward work the same way. On a static site there's no backend to ask, so the browser follows links itself. After a move to a new path, it scrolls to the top (or back to where that history entry was) and moves focus to the <h1>. A move within a page (a tab, a filter) keeps both. Moves between paths animate as view transitions, unless the reader has reduced motion on.

Views and components#

view! {
    <li class="flex gap-3" class:opacity-60=item.done>
        <input type="checkbox" checked=item.done on:change=Check(item.id.clone(), !item.done) aria-label="Done">
        <span class="flex-1">{&item.name}</span>
        {item.expires.map(|at| view! { <Time {at} /> })}
    </li>
}
  • Text goes in quotes, and everything is escaped. {…} takes text, numbers, a View, an Option or an iterator of views.
  • class="…" is literal, so Tailwind finds every class. class:name=cond adds one when cond holds; class=expr adds classes from a value. They're joined into one attribute by cn.
  • on:click= takes an action or a Datastar expression in quotes. bind:draft binds a signal and show="$open" shows and hides. Nothing built from data can become code.
  • view! produces maud's Markup, so html! still works beside it.

Errors point at the app's own source and say what to write instead.

A component is a function:

#[component]
pub fn ItemRow(item: &Item, compact: bool, class: Class) -> View {
    view! { <li class="flex gap-3 py-3" class:py-1=compact class=class>{&item.text}</li> }
}
// <ItemRow {item} compact class="mt-2" />

Props are named arguments. Each is required unless it's a bool, an Option, class, attrs, children or marked #[prop(default)]. A missing prop is a compile error naming it. Components render on the backend like pages: no JavaScript, nothing to hydrate.

The SDK's components cover what most apps need: Button, Input, Textarea, Select, Field, Card, Chip, Tabs, Dialog, Menu, EditInPlace, Lists (drag between lists), Time, Clock, Countdown, History, Empty, Avatar. The reference lists their props.

What a page shows belongs in its address. The path is the place; the query refines it (a filter, a tab, an open dialog). So a reload, Back and a shared link all keep it, and two tabs each show their own.

Actions and forms#

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

#[derive(Form)]
pub struct NewItem {
    #[form(max = 200)]
    pub name: String,
    pub expires: Option<u64>,
}

#[action]
pub async fn add_item(cx: &mut Act<Params>, form: NewItem) -> Result {
    cx.act(Command::AddItem { shelf: cx.params.shelf.clone(), id: new_id(), name: form.name, expires: form.expires }).await?;
    Ok(())
}
  • A view names an action in CamelCase: <form action=AddItem> posts to add_item, and on:click=Remove(id) posts id to remove. The action's URL is its route's, filled in from the page, so it gets the page's Params and nobody writes a URL.
  • #[derive(Form)] parses the posted form into typed fields and checks them (min, max, message). A field that fails goes back to the form with its message, and the action doesn't run.
  • After an action, every open page re-renders. The form that posted is cleared, except fields the action keeps (cx.keep(&["kind"])). An action can also move the page (cx.go), show a message (cx.say) or clear signals (cx.clear).
  • A #[download] is a file the page offers (a calendar entry, an export), made when it's asked for: <a href=Calendar download>.

Live pages#

Each open page holds one Datastar stream. When anything changes, the backend renders the page again and Datastar morphs in what's different. How "anything changes" is known depends on the backend:

  • Server: a change re-renders the open pages that read it. A page that called cx.listen(topic) re-renders for changes that touch that topic: on events, the model says what each event touches (Model::touches, so an undo or another server's change says it too); on app!(plain …), the action does (cx.notify(topic)). A page that never called listen re-renders for every change, and the acting session's own pages always do. Under soda dev, each page that listens is checked: after a change it wasn't drawn again for, it's drawn as a stranger would see it, and one that comes out different says so over it ("/b shows what bump_a changed, but doesn't listen for it"), since someone else's copy of it would go out of date. A topic it listen_softlys for re-renders it at most once a second (a count that every change touches). Who's here, names and the clock re-render only the pages that read them (cx.here(), cx.name_of, cx.now()), at most once a second each when they crowd in. A page whose tab is hidden waits until it's shown. Changes that come while a page is drawn make one more drawing, however many there were. Each drawing sends the whole page, but the stream is compressed across drawings (zstd in Chrome and Firefox; in Safari gzip while drawings fit its 32 kB window, brotli once they don't), so one much like the last costs what changed: a kanban board's 171 kB drawing goes as about 1 kB. Past a quarter of the machine's memory in encoders, a new stream takes a cheaper encoding its browser takes, or goes uncompressed. Everything else the server answers is compressed too. An app can limit what one person or network does at once (app!(…, limits = …): actions a second, pages open), how many pages it has room for (past that, a page waits in line), and what it sends in a day. A session nothing has used for ten minutes is forgotten, and taken back from its cookie if it comes again.
  • Local-first: the engine re-renders when it folds a new event, yours or a member's.
  • Static: pages don't change once built. Under soda dev, each has a stream so patches show.

Browser components#

Anything that must run in the browser (a ticking countdown, dragging, a chart) is a web component in web/components/. Each file there loads itself, and can import npm packages:

// web/components/expiry.js
import { component } from '/soda-component.js'

component('pantry-expiry', {
  props: ({ number, string }) => ({ at: number, label: string.default('Use by') }),
  parts: ['badge'],
  render: ({ html, props, part }) => html`
    <span class="${part('badge', 'inline-flex gap-1.5 rounded-pill bg-subtle px-2.5 text-sm')}">
      <span class="text-muted">${props.label}</span>
      <soda-time at="${props.at}" format="ago"></soda-time>
    </span>`,
})

In view! it's used like any element: <pantry-expiry at=item.expires />. It's written with the same Tailwind utilities as the views, and each named part takes classes from outside (badge-class="…"), merged after its own.

Styling#

Styling covers the look: Tailwind v4, with every color, font, radius and shadow a token, and a check that refuses anything else. Under it are three pieces:

  • cn with no table. A class given to a component must win over the component's own. The build reads what each utility sets off the app's compiled stylesheet (app.classes.json), and cn drops a class when a later one sets the same properties. It's exact for the app's own utilities and can't drift from Tailwind.
  • One stylesheet in every shadow root. The build writes app.styles.js, the app's utilities as one CSSStyleSheet that every component adopts. The tokens reach in by inheritance. One shared sheet costs tens of milliseconds where a sheet per component costs hundreds or more.
  • class: names reach Tailwind. The build lists the classes class: directives use (scripts/view-classes.mjs), and the token check checks them too.

soda dev#

soda dev builds, serves and watches the app. It uses Dioxus's Subsecond to patch changed Rust into the running program, so nothing restarts:

You changeWhat happensAbout
A page, layout, component or actionPatched; the open pages re-render in place0.6 to 1.5 s
A new or removed route filePatched like an edit1.2 to 1.7 s
A style, token or classThe stylesheet is swapped in place0.2 to 0.3 s
A type's shape, Cargo.tomlA full build and restart, then a reload that keeps your place5 to 6 s
A mistakeIt's shown over the page, with where, until it's fixed0.2 s for a typo; about 1.4 s for a compile error
A panicIt's shown over the page, with where; fixing it brings the page backabout 1 s

What the app holds survives every patch: a server's state, sessions and open pages, or a local-first app's data, which lives in the browser. For a local-first app, soda dev also runs a store of its own over SQLite, so nothing but Rust and the CLI is needed. Hot-patching explains how the patching works.

Backends#

A backend is where an app runs. The framework doesn't depend on any of them; each depends on the framework and implements its seam. src/main.rs names one:

soda_server::app!(board::Board);       // a server, storing a model's events
soda_server::app!(board::Board per board); // the same, a model for each [board] in the address
soda_server::app!(plain list::List);   // a server, storing its own state
soda_local::app!(model::Items);        // local-first, in each person's browser
soda_static::app!(site::Site);         // static, rendered at build time
Framework (soda)ServerLocal-firstStatic
State—A soda::Model's events, or any Send + Sync state (start)The open space's modelWhat load reads at build time
Per person—A session, in a sealed cookieA device, with its own keysNothing: every reader sees the same page
Actions#[action], #[derive(Form)]cx.act(command), or async code with the sessioncx.act(command): signed, sealed, syncedNone (refused, saying why)
RedrawsThe stream, morphsAfter every action (by topic on plain)When an event is foldedNever, once built
Browser codesoda.jsNothing moresoda-local.js: passkeys, the worker, syncNothing more

The seam#

pub trait Backend: 'static {
    /// What a page reads beyond its address. `Cx` derefs to it.
    type Read<'a>: Reads + Clone;
    /// What an action can do beyond answering the page. `Act` derefs to it.
    type Write: Writes;
}
pub trait Reads { fn recall(&self, key: &str) -> Option<String>; fn note(&self, key: &str, value: Option<&str>); fn now_ms(&self) -> u64; }
pub trait Writes { fn say(&mut self, words: String); fn remember(&mut self, key: &str, value: Option<String>); }

Cx keeps what's the framework's (params, page, links, the query) and derefs to the backend's Read. Act does the same for Write. So what a page reads beyond its address is the backend's:

BackendA page reads
Server, on eventscx.app (the model), cx.me (who's looking), cx.history(), cx.here(), cx.undo(), and with per, cx.spaces()
Server, plaincx.state (the app's state), cx.session
Local-firstcx.app (the open space's model), cx.space, cx.me
Staticcx.state (what load read)

On a server or a static site, pages, layouts, heads and downloads may be async fn; the router awaits them. soda::backend::Bare, a backend that reads only the address, is what Soda's own tests run on.

On a server#

soda-server serves the app with axum:

RequestAnswer
GET /any/pathThe shell with the page rendered in it, and a session for a new browser
GET /api/stream?page=…The page's Datastar stream: rendered now, then after every change
POST /api/pageThe page moved to another address
POST /api/_/<route>/<action>Runs an action
GET /api/_/<route>/<download>A download
/api/undo, /api/redo, /api/scrub, /api/me, /api/focusOn events: undo, history, names, presence
Anything elseA file from dist/, or on app!(plain …) the app's own routes (App::routes)

A session is a random id and its memory, in a cookie the server seals with its key (soda-session). The key and the app's files live in its data folder (SODA_DATA, data/ by default), so a restarted server takes every browser back as it was. soda deploy builds a container image, or with --to ssh://… runs it on any Docker host.

On events (the default), the app is a soda::Model: decide turns a command into events, evolve applies one, and step and travel undo. soda::timeline::Timeline folds the changes into the state now, the state after any change, the history in words, and each person's undo. soda-store keeps the events in SQLite or Postgres, and checks every append against the shapes events.lock records. Events covers the model.

app!(board::Board per board) makes each [board] in the address a model of its own: its own stream in the store (app:<board>), history, undo, who's here and open pages. A change in one draws only that board's pages, and changes to different boards don't wait for each other. A board is read from the store when a page first opens it, and let go (saving a checkpoint, if the model saves them) once no page has had it open for ten minutes. A page outside [board] (/, listing them) reads cx.spaces(): each board with something kept in it, and when it last changed. Its cx.app is a model with nothing in it, and it can't act. Every request soda.js sends to /api/ says which page sent it (Soda-At), so Undo, history, names and presence go to that page's board. per board with no [board] folder in src/routes doesn't compile.

A page that shows everyone at its address the same takes &Everyone<Params> in place of &Cx<Params>. Everyone reads what Cx does of the app (cx.app, who's here, the history, the address and links, the clock) and nothing of who's looking: a page that reads cx.me, the session or undo doesn't compile. So the server draws it once a change for each address, the first page there to be drawn again drawing it and the rest taking that drawing, and keeps it while a page shows it. What's each person's own goes in <Mine with=you />: fn you(cx: &Cx) -> View is drawn for each of them into the drawing they share (their name, their Undo). What's marked data-person with someone's id is marked data-you on their page, so their own roundel can be ringed and their own "is editing" tag hidden with no <Mine> at all. Layouts on &Everyone around it are drawn into it too (the board's sign and history line); a layout on &Cx, and the head, are drawn for each person around it, and someone looking back at the history has the page drawn for them alone. A thousand pages on the kanban template, drawn for each change, cost the server 673% of a core; on Everyone, 193% (soda load counts the shared drawings by route).

// src/routes/b/[board]/page.rs
pub fn page(cx: &Everyone<Params>) -> View {
    view! {
        <p>{cx.app.count} " bumps, " {cx.here().len()} " here"</p>
        <Mine with=you />
    }
}

fn you(cx: &Cx) -> View {
    view! { <p>"You're " {&cx.me.name}</p> }
}

Local-first#

soda-local runs the app in each person's browser, in its service worker. Each space is a signed, encrypted log, synced through a store that can't read it. Accounts, passkeys, devices, sharing, presence and undo come with it. The address names the space (/~3fa9c2e1b0/shelves/rice), so two tabs can show two spaces. The model is the same soda::Model a server runs. Local-first builds one, and the engine explains how it stays correct.

Static#

soda-static renders every page once, at build time, into files. A route with params lists its pages with params(cx) -> Vec<Params>; leaving it out is a compile error. not_found.rs becomes 404.html, each page's head fills its <title>, description and og: tags, and when the site sets its url the build writes a sitemap. Actions, #[prerender], and downloads that take arguments or sit under params are refused. Under soda dev, it serves its pages like a server and re-renders them when a file WATCH names changes. sodakit.dev is one. Static sites builds one.

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

Esc