Chat Rooms
elements man recipes/chat-roomsA multi-room chat app with handle-only login. A user picks a handle on the home
page, sees a list of rooms, optionally creates a new one, then clicks into
/rooms/:id for a per-room message stream. Two LiveTables drive the recipe: a
rooms LiveTable opened whole, which every browser watches, and a messages
LiveTable opened per room as a window, view({ roomId }, { orderBy, limit }),
so a message reaches only the browsers viewing its room, and a browser holds the
newest fifty messages, not the room's whole history.
Handle-only login: the user types a handle, the server creates a chatUsers
row, and there is no password. Two browsers can share a handle, because the
identity is the row id.
Migration
Terminalelements create migration 'add chat' -tables=chatUsers,chatRooms,chatMessages
app/migrations/<timestamp>-add-chat.migration.sql-- add chat -- 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 chatUsers ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), handle text not null ); create trigger chatUsersTouchUpdatedAt before update on chatUsers for each row execute function touchUpdatedAt(); create table chatRooms ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), name text not null ); create trigger chatRoomsTouchUpdatedAt before update on chatRooms for each row execute function touchUpdatedAt(); create table chatMessages ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), roomId uuid not null references chatRooms(id) on delete cascade, userId uuid not null references chatUsers(id) on delete cascade, userName text not null, body text not null ); create index chatMessagesRoomIdx on chatMessages (roomId, createdAt desc, id desc); create trigger chatMessagesTouchUpdatedAt before update on chatMessages for each row execute function touchUpdatedAt(); -- Broadcast writes that do not come from a live view (a job, an rpc, -- `elements db -sql`) to every open page. Writes through the view broadcast -- themselves; see `elements man recipes live-from-sql`. create or replace function chatMessagesNotify() returns trigger language plpgsql as $$ declare r record; payload text; begin r := coalesce(new, old); payload := json_build_object( 'op', lower(tg_op), 'data', json_build_object( 'id', r.id, 'createdAt', json_build_object('$type', 'Date', '$value', (extract(epoch from r.createdAt) * 1000)::bigint), 'roomId', r.roomId, 'userId', r.userId, 'userName', r.userName, 'body', r.body ) )::text; -- NOTIFY takes under 8000 bytes. A larger row goes as its id, and the -- server reads the row back. if octet_length(payload) >= 8000 then payload := json_build_object('op', lower(tg_op), 'id', r.id)::text; end if; perform pg_notify(channel_name('chat_messages'), payload); return r; end; $$; create trigger chatMessagesNotifyTrigger after insert or update or delete on chatMessages for each row execute function chatMessagesNotify();
chatUsers.handle is not unique: the row id is the identity. chatMessages.userName
is denormalized from chatUsers.handle at write time so a rename does not
rewrite chat history. chatMessagesRoomIdx matches the room page's window,
where roomId = $1 order by createdAt desc, id desc, so every page reads the
index instead of sorting the room.
LiveTables
Both pages open these tables, so they live in app/shared/services/ rather
than in either page's template.ehtml.
app/shared/services/chat.tsimport { LiveTable, session } from "@elements/app"; export interface Room { id: string; createdAt: Date; name: string; } export interface Message { id: string; createdAt: Date; roomId: string; userId: string; userName: string; body: string; } export let chatRooms = new LiveTable<Room>(); export let chatMessages: LiveTable<Message> = new LiveTable<Message>({ insert: (item) => { session.isLoggedInOrThrow(); return chatMessages.insert(item); }, });
A LiveTable takes its table from the variable name, camelCase to snake_case,
so chatRooms reads chat_rooms; name the variable after the table and they
cannot drift. The table's name is also its channel, so the trigger above
notifies chat_messages and every view of the table hears it.
chatRooms has no partition: every browser on the home page sees a new room the
moment someone creates it. chatMessages is opened per room below with
view({ roomId }, window), so a message reaches only the views whose roomId
it matches, and the window keeps each browser's copy to the pages it has
loaded. The insert handler requires a logged-in session, which after the
handle login means a chatUsers row exists, then runs the raw auto-SQL on the
declaration. The explicit LiveTable<Message> annotation is there because the
initializer refers to the declaration.
Home page
Terminalelements create page home
The home page renders one of two views: an unsigned-in handle entry form, or a
signed-in room list with a create-room form and a logout button.
session.isLoggedIn() is reactive in the browser, so submitting the handle
login flips the view without a full page reload.
The three RPC functions belong to this page alone, so they live in its
template.ehtml.
signin inserts a fresh chatUsers row and binds the session to it.
createRoom returns the new room's id so the handler can navigate to
/rooms/:id immediately. signout ends the session, and with it every live
view that session opened, so follow it with a redirect. See the note below.
app/pages/home/index.tsimport { Request, Response } from "@elements/app"; import home from "./template"; import { chatRooms } from "#app/shared/services/chat"; export default function route(req: Request, res: Response) { return new home({ rooms: chatRooms.view() }); }
app/pages/home/template.ehtmlimport "./style.css"; import { LiveView, sql, session, redirect, ValidationError } from "@elements/app"; import { Button } from "@elements/ui/button"; import { Empty } from "@elements/ui/empty"; import { Field } from "@elements/ui/field"; import { Input } from "@elements/ui/input"; import { Item, ItemGroup } from "@elements/ui/item"; import { Room } from "#app/shared/services/chat"; /** @rpc */ export function signin(handle: string) { if (handle.trim().length === 0) { throw new ValidationError("handle is required"); } let user = sql<{ id: string }>( ` insert into chatUsers ( handle ) values ( ${handle.trim()} ) returning id `, ).firstOrThrow(); session.login({ userId: user.id, userName: handle.trim(), }); } /** @rpc */ export function signout() { session.logout(); } /** @rpc */ export function createRoom(name: string): string { session.isLoggedInOrThrow(); if (name.trim().length === 0) { throw new ValidationError("room name is required"); } return sql<{ id: string }>( ` insert into chatRooms ( name ) values ( ${name.trim()} ) returning id `, ).firstOrThrow().id; } function onSigninSubmit(handle: { value: string }) { signin(handle.value); handle.value = ""; } function onCreateRoomSubmit(name: { value: string }) { let id = createRoom(name.value); name.value = ""; redirect(`/rooms/${id}`); } <html class="page-home" ( rooms: LiveView<Room>, private handle: { value: string } = { value: "" }, private newRoom: { value: string } = { value: "" }, )> <main class="page-shell"> <h1>chat</h1> <form e:if={!session.isLoggedIn()} class="stack" onsubmit={() => onSigninSubmit(handle)}> <Field label="pick a handle to join the chat" required> <Input value={handle.value} placeholder="alice" /> </Field> <Button type="submit" variant="primary">join</Button> </form> <div e:else class="stack"> <p class="row"> signed in as <strong>{session.get('userName')}</strong> <Button size="sm" variant="ghost" onclick={() => signout()}>sign out</Button> </p> <h2>rooms</h2> <ItemGroup label="rooms"> <Item e:for={r of rooms.sort((a, b) => +a.createdAt - +b.createdAt)} href={`/rooms/${r.id}`} title={r.name} /> </ItemGroup> <Empty e:if={rooms.length === 0} title="no rooms yet" description="create one below." /> <form class="row" onsubmit={() => onCreateRoomSubmit(newRoom)}> <Input value={newRoom.value} placeholder="new room name" required attrs={{ "aria-label": "new room name" }} /> <Button type="submit">create room</Button> </form> </div> </main> </html>
The two branches share the same template instance. After signin
returns, session.isLoggedIn() is true on the browser; the e:if/e:else
switches and the rooms view renders. New rooms from any browser appear in the
list immediately because chatRooms is a live, broadcasting LiveTable.
The widgets are @elements/ui templates (elements man ui): a
Field (opens in a new tab) around an Input (opens in a new tab) and a
Button (opens in a new tab) for each form, an
ItemGroup (opens in a new tab) of link Items for the rooms, and an
Empty (opens in a new tab) until the first room exists.
Room page
Terminalelements create page room
The room page renders the message feed and a composer. Inserting a message goes through the room's view, which broadcasts to every browser watching that room.
app/pages/room/index.tsimport { Request, Response, sql, session } from "@elements/app"; import room from "./template"; import { Room, chatMessages } from "#app/shared/services/chat"; export default function route(req: Request, res: Response) { session.isLoggedInOrThrow(); let roomId = req.params.id; let row = sql<Room>(` select id, createdAt, name from chatRooms where id = ${roomId} `).firstOrThrow("room not found"); return new room({ room: row, messages: chatMessages.view({ roomId }, { orderBy: "createdAt desc", limit: 50, }), }); }
The route guards on a logged-in session and resolves the room before opening
the partition; firstOrThrow gives a 404 when the room id does not exist.
The second argument is the window: the newest fifty by createdAt, tie-broken
on id. A new message sorts before the loaded range and is admitted live; an
older page arrives only when the user asks. See elements man livetable/windows.
app/pages/room/template.ehtmlimport "./style.css"; import { LiveView, session } from "@elements/app"; import { Button } from "@elements/ui/button"; import { Input } from "@elements/ui/input"; import { Message, MessageContent } from "@elements/ui/message"; import { MessageList, MessageListEmpty } from "@elements/ui/message-list"; import { Room, Message as ChatMessage } from "#app/shared/services/chat"; function onSubmit(feed: LiveView<ChatMessage>, draft: { value: string }) { feed.insert( { userId: session.getOrThrow('userId'), userName: session.getOrThrow('userName'), body: draft.value, }, () => draft.value = "", ); } <html class="page-room" ( room: Room, messages: LiveView<ChatMessage>, private draft: { value: string } = { value: "" }, )> <div class="app is-fixed"> <header class="page-shell row"> <h1>{room.name}</h1> <a href="/">back to rooms</a> </header> <main class="app-main page-shell"> <MessageList label={room.name}> <div e:if={messages.hasMore} class="center"> <Button size="sm" variant="ghost" onclick={() => messages.more()}>load older</Button> </div> <MessageListEmpty e:if={messages.length === 0} /> <Message e:for={m of messages.toReversed()} author={m.userName}> <MessageContent>{m.body}</MessageContent> </Message> </MessageList> </main> <footer class="page-shell"> <form class="row" onsubmit={() => onSubmit(messages, draft)}> <Input value={draft.value} placeholder={`message in ${room.name}`} required attrs={{ "aria-label": "message" }} /> <Button type="submit" variant="primary">send</Button> </form> </footer> </div> </html>
The view holds its rows in window order, newest first, so toReversed() puts
the oldest loaded message at the top without a sort per render. messages.more()
fetches the fifty before the oldest loaded row and adds them to the view, and
hasMore turns false when a page comes back short, which removes the button.
The feed is a MessageList (opens in a new tab) of
Message (opens in a new tab) rows, each named by its author. The list
fills the height it is given and stays pinned to the newest message until the
reader scrolls up, so the page is the .app.is-fixed shell
(elements man style/layout): header and composer keep their height, main
takes the rest, and the list scrolls inside it. The shared Message interface
is imported as ChatMessage because the template takes that name.
Day separators and author grouping go on the row as e:if flags, never as a
loop inside the loop, and reactions are stored on the message row so they
page with the window: elements man recipes/grouped-feed has both.
messages.insert(...) passes every field the feed reads: userId, userName,
and body. The partition fills the roomId column on insert. The resetUI
callback clears the draft the moment the optimistic row lands.
Routes
Register the pages in index.ts:
index.tsimport home from "#app/pages/home"; import room from "#app/pages/room"; // ... app.route("/", home); app.route("/rooms/:id", room);
Notes
- Sign out, then navigate. Call
redirect("/")aftersignout()and the new page opens a fresh view: a view is authorized once, for the user whose route opened it, sosession.logout()closes that session's views. A view opened anonymously is public and keeps running through a signin; redirect after signin only when the view is partitioned onuserId. Full rule:elements man session. - Display a timestamp? Pass one at insert. If the feed shows
{formatTime(m.createdAt)}, passcreatedAt: new Date()in the insert payload so the optimistic row renders its timestamp immediately. The server'snow()replaces it on reconcile. - Ephemeral users. Every
signincall inserts a newchatUsersrow, so signing in twice gives twouserIdvalues. To keep a handle's history, look up an existing row by handle first and insert only when it is missing. - Denormalized userName.
chatMessages.userNameis copied fromchatUsers.handleat write time, so old messages keep the handle they were sent under. This is what you want for a chat log. - Room deletion.
on delete cascadeonchatMessages.roomIdremoves a room's history with the room. A "delete room" button callsrooms.delete(room)from the home page; who may delete goes in adeletehandler on thechatRoomsdeclaration. - Password login. Build the auth flow from
elements man recipes authenticationand replacesigninwith its password-based signin. The rest of this recipe is unchanged. - Typing indicators and presence. Channel-driven UX over the same room:
elements man recipes typing-indicatorandelements man recipes presence.