LiveTable
elements man livetableA LiveTable selects, inserts, updates, and deletes rows with SQL it writes,
broadcasts each write to every browser that renders those rows, and updates
the browser's reactive HTML optimistically. In practice: declare a LiveTable
on the server, open a view of it in the route, pass that view to the page as a
template attribute, and iterate it with e:for. The page server-renders with
the rows in the first response. When the browser inserts, updates, or deletes a
row, the UI changes immediately, and the server then writes the row and broadcasts
it.
When another browser mutates the same table, the server sends the row over
each watching browser's WebSocket and each browser patches the affected row in
place. A write on any app server is sent to watching browsers on every app
server: the write notifies the table's channel in the shared Postgres
database, and every app server listens on that channel.
Despite the name, a LiveTable is not tied to one database table. It is a live
set of rows the browser holds and keeps in sync with the server: the rows
arrive in the first render, then insert / update / delete events stream in and
patch them. With zero config it mirrors a single table. With a custom select
its rows can be a join or a projection.
A LiveView is data: an iterable of rows, read like an array, that templates
render with e:for. The page renders it on the server in the first response,
and in the browser after that. The server sends row changes, never HTML, and
the template's state is held in the browser.
Every write through a LiveView is sent to every watching browser, whether it comes
from a browser, a route, an @rpc, a job, or a test. To make writes from psql
or a plain sql() call live as well, add a Postgres trigger that notifies the
table's channel; see elements man recipes/live-from-sql. A LiveView write
sends the broadcast. A plain sql() call writes the table and sends no
broadcast, so the trigger sends the notification for that write. With the trigger in place every write is live
whatever its source, and you can test a page by changing the database directly.
LiveTable and LiveView: the two types
There are two types, and every page in this topic uses both names.
A LiveTable is the declaration: the columns, the handlers, the channel. It is declared once, at module scope, and it is server-only, because it configures a database and a channel, neither of which a browser has. You never read rows from it and you never write through it.
A LiveView is one request's rows. table.view() in the route reads them
and opens the subscription that keeps them current. The template renders
that view, the server sends that view's rows to the browser, and every write
goes through that view.
services.tsthe declaration, and a write that any caller can reachexport const comments = new LiveTable<Comment>(); export function postComment(view: LiveView<Comment>, text: string) { view.insert({ text, author: session.getOrThrow("userName"), }); }
route.tsthe viewreturn new html({ comments: comments.view() });
Reading rows from a LiveView
A LiveView is an iterable of rows, and every read on it is the matching Array
method over a copy: filter, sort, map, find, at, slice, length,
and the other non-mutating Array methods, plus get(id). They return
plain arrays and mean exactly what they mean on an array.
An expression that uses one of those methods, or iterates the view itself, is
evaluated again when a row is added to the view, removed from it, or moved in
its order. So an e:for over the view is live, an e:for over
comments.sort(byTime) is live, and an e:for over a helper that builds its
own array from the view is live too, for the same reason: the loop evaluates
its expression again and matches the new rows to the rendered rows by id. A row's fields are
watched separately, so a change to one field repaints the bindings that read
it and nothing else.
Template<li e:for={c of comments}>{c.text}</li> <li e:for={c of comments.sort((a, b) => +a.createdAt - +b.createdAt)}>{c.text}</li> <li e:for={line of feed(comments)}>{line.text}</li> <span>{comments.length}</span>
All four lines above work the same way. Filter, sort or map the rows in the expression to fit the page.
At a Glance
app/shared/services/comments.tsimport { LiveTable } from "@elements/app"; interface Comment { id: string; text: string; author: string; createdAt: Date; } export let comments = new LiveTable<Comment>();
app/pages/comments/index.tsimport { Request, Response } from "@elements/app"; import { comments } from "#app/shared/services/comments"; export default function route(req: Request, res: Response) { return new html({ comments: comments.view() }); }
app/pages/comments/template.ehtmlfunction onSubmit(comments: LiveView<Comment>, form: { text: string }) { comments.insert({ text: form.text, author: session.get("userName")!, createdAt: new Date(), }, () => form.text = ""); } <html ( comments: LiveView<Comment>, private form: { text: string } = { text: "" }, )> <ul> <li e:for={comment of comments.sort((a, b) => +a.createdAt - +b.createdAt)}> <strong>{comment.author}</strong>: {comment.text} </li> </ul> <form onsubmit={() => onSubmit(comments, form)}> <input value={form.text}> <button>post</button> </form> </html>
The sequence, from page load to a posted comment:
- The page server-renders with the current comments. First paint has data.
comments.insert(...)adds the row optimistically. The UI shows it at once.- The server persists it and broadcasts to every browser watching the table, on every app server.
- Every other browser receives the broadcast and its
e:forplaces the row. - The
resetUIcallback runs as soon as the optimistic row is added in the browser, before the server has confirmed. Use it to clear the form state the insert read, so the form is empty for the next comment without waiting for the server's reply.
A view opened while logged in belongs to that session and stops when it ends. On
session.logout(), expiry, or session.revoke(), the server stops the view's
subscription and the browser drops it, so the rows freeze at their last state.
The route authorized that view for that user, and the check does not re-run
when the user changes.
Views opened by an anonymous request are public and keep running, and the
WebSocket stays open. To get live rows again, open a new view: navigate to the
page again or return one from an @rpc. See elements man session.
The other pages in this topic: options for the declaration,
partitions for a view of the rows that match a column value, windows for
paging a long
table, mutations for the three writes, and handlers for custom SQL and
authorization.