Live Comments
elements man recipes/live-commentsA single-stream chat feed with a composer pinned to the bottom: type a message,
hit enter, the message appears immediately in your feed, and every other browser
watching the feed, on every app server, sees it the moment the server
broadcasts. One LiveTable and
one <form> drive it. No RPC functions to write, no polling, no manual
subscribe/unsubscribe.
LiveTable.insert(...) adds the row optimistically. The local feed paints the
new message before the server has acknowledged. The resetUI callback clears
the draft as soon as the optimistic row is added to the feed, so the input is
ready for the next message before the server replies.
Migration
Terminalelements create migration 'add users and comments' -tables=users,comments
app/migrations/<timestamp>-add-users-and-comments.migration.sql-- add users and comments -- Auto-update updatedAt on row changes. create or replace function touchUpdatedAt() returns trigger language plpgsql as $$ begin new.updatedAt = now(); return new; end; $$; create table users ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), handle text not null unique, passwordHash text not null ); create trigger usersTouchUpdatedAt before update on users for each row execute function touchUpdatedAt(); create table comments ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), userId uuid not null references users(id) on delete cascade, userName text not null, body text not null ); create trigger commentsTouchUpdatedAt before update on comments for each row execute function touchUpdatedAt();
comments.userName is denormalized: the user's display name is copied at write
time. A later rename does not change the name on old messages, so the log shows
each message under the name its author had then. To show the current handle
instead, drop the column and join users in a custom select.
For the signin/signup pages, see elements man recipes authentication.
Page setup
Terminalelements create page chat
The Comment interface and the comments LiveTable are used only by the
/chat page, so they are declared in the page's template.ehtml. The route
requires a logged-in session, opens a view and passes it to the template; the
template iterates the view and inserts new rows from the composer.
app/pages/chat/template.ehtmlimport "./style.css"; import { LiveTable, LiveView, session } from "@elements/app"; import { MessageList } from "@elements/ui/message-list"; import { Message, MessageContent } from "@elements/ui/message"; import { Input } from "@elements/ui/input"; import { Button } from "@elements/ui/button"; export interface Comment { id: string; createdAt: Date; userId: string; userName: string; body: string; } export let comments: LiveTable<Comment> = new LiveTable<Comment>({ insert: (item) => { session.isLoggedInOrThrow(); return comments.insert({ ...item, userId: session.getOrThrow("userId"), userName: session.getOrThrow("userName"), }); }, }); export function onSubmit( view: LiveView<Comment>, body: string, onSent?: () => void, ): void { view.insert( { userId: session.getOrThrow("userId"), userName: session.getOrThrow("userName"), body, }, onSent, ); } <html class="page-chat" ( comments: LiveView<Comment>, private draft: string = "", )> <main class="page-shell chat"> <MessageList label="Comments"> <Message e:for={c of comments.sort((a, b) => +a.createdAt - +b.createdAt)} from="user" variant="flat" align="start" author={c.userName} showAvatar> <MessageContent>{c.body}</MessageContent> </Message> </MessageList> <form class="row" onsubmit={() => onSubmit(comments, draft, () => draft = "")}> <Input value={draft} placeholder="say something" required /> <Button type="submit" variant="primary">send</Button> </form> </main> </html>
app/pages/chat/style.css@import "#app/shared/styles/page.css"; .page-chat .chat { display: flex; flex-direction: column; height: 100dvh; } .page-chat .chat form input { flex: 1; }
The page is a column the height of the viewport. MessageList fills the height the
composer leaves, keeps the newest message in view until the reader scrolls up,
and scrolls inside itself, so the composer stays pinned to the bottom. Each
comment is a Message with its author's name and initials.
onSubmit is exported even though the template is the only caller, because
an .ehtml file is a module: index.ts and a sibling test.ts both import from
./template by name, and the function works unchanged from a route, an @rpc,
or a job (elements man livetable/mutations).
onSubmit takes the view as a parameter because an insert is made through a
view. comments above is the declaration: it configures the table and
has no rows and no mutators. The template passes the view the route opened, and
a test passes one of its own.
The e:for above sorts the comments by createdAt, oldest first, so a new
message renders at the bottom. The sort runs in the template; the query has no
order by.
from="user" says every sender is a person; variant="flat" and
align="start" keep every message on the left, where a group chat reads
best.
The insert handler runs on the server for every insert a client makes. It
calls session.isLoggedInOrThrow(), so an anonymous client that calls
insert(...) directly gets AuthError before any row is written. It then sets
userId and userName from the session, so every stored comment names its
real author. comments.insert(...) inside the handler runs the LiveTable's
generated statement, one insert ... returning against the table; the
LiveTable infers the columns from the table. The declaration carries an explicit LiveTable<Comment>
annotation because its initializer refers to it.
app/pages/chat/index.tsimport { Request, Response, session } from "@elements/app"; import chat, { comments } from "./template"; export default function route(req: Request, res: Response) { session.isLoggedInOrThrow(); return new chat({ comments: comments.view() }); }
The route requires a logged-in session and passes a view of the LiveTable to the template. Elements server-renders the initial messages into the HTML, so the first paint already has data, and the browser receives the same view, subscribed to later changes.
onSubmit passes every field the feed renders, userName in particular,
because the optimistic row is painted from exactly that object. resetUI clears the draft as soon as the optimistic row
is added to the feed in the browser, so the input empties before the server
replies over the WebSocket.
The e:for is patched per row. Inserting one message into a thousand-message
feed touches only the new Message; the existing rows don't re-render.
Routes
Register the page in index.ts:
index.tsimport chat from "#app/pages/chat"; // ... app.route("/chat", chat);
Notes
- Pass every field the template reads. The optimistic row renders before the server replies, from the payload you pass. Pass every field the template reads, and the optimistic row renders with no field missing.
- Display a timestamp? Pass one at insert. If you add
{formatTime(c.createdAt)}to the feed, passcreatedAt: new Date()in the insert payload so the optimistic row renders its timestamp immediately. The server'snow()value replaces it when the server's row arrives. - The author comes from the session. The browser passes
userIdanduserNameso the optimistic row renders at once; the handler overwrites both fromsession, so the stored row always names the signed-in user. - Edits and deletes. Add an
updatehandler that callssession.isLoggedInOrThrow(), refuses another user's row withif (item.userId !== session.getOrThrow('userId')) { throw new ForbiddenError(); }, then returnscomments.update(item), and the matchingdelete. ImportForbiddenErrorfrom@elements/app. The template gains an "edit" button per row that callscomments.update({ ...c, body: edited }). - Per-room threads. Open the view on a partition from the route:
comments.view({ roomId: req.params.roomId }). A comment reaches only the browsers viewing its room, the partition fillsroomIdon insert, and every mutation is checked against the room. The full worked example iselements man recipes chat-rooms. - Writes from jobs and psql. Add a Postgres trigger that notifies the
table's channel,
channel_name('comments'), with{ op, data }, and a job, cron task, or psql session inserting intocommentsshows up live on every app server, alongside the app's own broadcasts: the browser dedupes by id. Seeelements man recipes live-from-sqlfor the trigger.