Typing Indicator
elements man recipes/typing-indicatorA "someone is typing..." indicator for a chat page. The browser calls an
RPC function as the user types into the composer, at most once every 1.5
seconds. The RPC function calls notify on a typing channel. Every other
browser receives the ping, adds the typer's name to a local list, and removes
the entry after a few seconds with no further pings. Typing pings are events,
not data rows, so the recipe uses a Channel: it broadcasts each notification
and stores nothing.
The recipe is a single-room chat for clarity. To use it in the
multi-room chat-rooms recipe, filter the channel's listen() on roomId.
Migration
Terminalelements create migration 'add chat messages' -tables=chatMessages
app/migrations/<timestamp>-add-chat-messages.migration.sql-- add chat messages -- 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 chatMessages ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), userName text not null, body text not null ); create trigger chatMessagesTouchUpdatedAt before update on chatMessages for each row execute function touchUpdatedAt(); -- Broadcast writes that do not come from a live view, so a message inserted by -- a job, an rpc, or `elements db -sql` still reaches every open page. Writes -- through the view broadcast themselves and need none of this; 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), '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();
Single-room chat means no roomId, no chatUsers table. userName is whatever
the user typed into the handle input on the page; this recipe has no sign-in,
so the code shown is mostly the channel.
Page setup
Terminalelements create page chat
The LiveTable, the Channel, and the RPC are all used only by the /chat page,
so they are declared in the page's template.ehtml. The route imports them
from there and passes the template a view of the messages LiveTable and a new
listener on the typing channel; the template subscribes to the listener in
oninit.
app/pages/chat/index.tsimport { Request, Response } from "@elements/app"; import chat, { chatMessages, typing } from "./template"; export default function route(req: Request, res: Response) { return new chat({ messages: chatMessages.view(), typing: typing.listen(), }); }
chatMessages is a LiveTable opened whole, with no partition. It is named
for the table the migration creates: a LiveTable takes its table from the
variable name, camelCase to snake_case, so chatMessages reads
chat_messages. The table's name is its channel too, which is what the
trigger notifies, so a message written outside the view reaches the page. typing is a
Channel: it
broadcasts pings but does not store them. Listeners receive the live
notifications and forget them after handling. Channel.notify is server-only, so
the browser calls the notifyTyping RPC function, and that function calls
typing.notify on the server. The RPC does no debouncing; the browser
decides how often to call.
The route passes the template a view of the messages LiveTable and a
Listener for the typing channel. The listener is serialized into the
response. When the page attaches in the browser, the listener connects to the
server over a WebSocket and starts receiving notifications.
app/pages/chat/template.ehtmlimport "./style.css"; import { Channel, LiveTable, LiveView, type Listener } from "@elements/app"; import { Button } from "@elements/ui/button"; import { Field } from "@elements/ui/field"; import { Input } from "@elements/ui/input"; export interface Message { id: string; createdAt: Date; userName: string; body: string; } export interface TypingPing { userName: string; } export let chatMessages = new LiveTable<Message>(); export const typing = new Channel<TypingPing>("typing"); /** @rpc */ export function notifyTyping(userName: string) { if (userName.trim().length === 0) { return; } typing.notify({ userName: userName.trim() }); } let lastNotifiedAt = 0; function onSubmit(messages: LiveView<Message>, userName: string, body: { value: string }) { if (userName.trim().length === 0) { return; } if (body.value.trim().length === 0) { return; } messages.insert({ userName: userName.trim(), body: body.value, }, () => body.value = ""); } function onType(userName: string) { if (userName.trim().length === 0) { return; } let now = Date.now(); if (now - lastNotifiedAt < 1500) { return; } lastNotifiedAt = now; notifyTyping(userName); } function onTypingPing(self: string, ping: TypingPing, typers: string[]) { if (ping.userName === self) { return; } if (!typers.includes(ping.userName)) { typers.push(ping.userName); } setTimeout(() => { let i = typers.indexOf(ping.userName); if (i !== -1) { typers.splice(i, 1); } }, 3000); } <html class="page-chat" ( messages: LiveView<Message>, typing: Listener<TypingPing>, private userName: string = "", private body: { value: string } = { value: "" }, private typers: string[] = [], ) oninit={() => typing.on("notify", (p) => onTypingPing(userName, p, typers))}> <main class="page-shell is-form"> <h1>chat</h1> <Field label="your name" class="me"> <Input value={userName} placeholder="alice" /> </Field> <ul class="feed"> <li e:for={m of messages.sort((a, b) => +a.createdAt - +b.createdAt)}> <strong>{m.userName}</strong>: {m.body} </li> </ul> <p e:if={typers.length > 0} class="typing"> {typers.join(", ")} typing… </p> <form class="row" onsubmit={() => onSubmit(messages, userName, body)}> <Input value={body.value} oninput={() => onType(userName)} placeholder="say something" required /> <Button variant="primary" type="submit">send</Button> </form> </main> </html>
Four parts:
onTypedebounces the outgoing pings. Every keystroke firesoninput, but the function only forwards tonotifyTypingevery 1.5 seconds. Without the check, the browser would call the RPC function on every character.lastNotifiedAtis module-level state, local to the template module.onTypingPingis the listener handler. It drops pings from the local user (otherwise "alice typing…" would show on alice's own screen), adds new typers to the array, and schedules asetTimeoutto remove the entry after 3 seconds with no further pings. A re-ping during that window starts a new timer; the entry stays as long as pings keep arriving.oniniton the template instance subscribes to the listener once. The handler capturesuserNameandtypersfrom the template's attributes.- The name is a
Fieldaround anInput, which wires the label to the control, and the composer is anInputwhoseoninputrunsonType. TheButtonsaystype="submit"because a button template istype="button"unless told otherwise.
Listener<TypingPing> is also a reactive value, but this recipe uses it as a
pure event stream via on("notify", ...). The typers array is what the
template binds to; pushing to it is enough to re-render the e:if.
Routes
Register the page in index.ts:
index.tsimport chat from "#app/pages/chat"; // ... app.route("/chat", chat);
Notes
- Why a channel and not a LiveTable. Typing pings are events, not rows. Storing them would mean inserting and deleting a row per keystroke, and broadcasting each of those writes. A channel sends each notification to its listeners and stores nothing.
- Multi-room version. In a multi-room chat
(
elements man recipes chat-rooms), includeroomIdon theTypingPinginterface and filter the listener:typing.listen({ filter: (p) => p.roomId === currentRoomId }). The filter runs on the server, so a ping for another room is never sent to the browser. - Self-filtering server-side. This recipe filters self pings in the browser.
To filter them server-side instead, give each ping a
clientId(an app-generated id the browser keeps inlocalStorage,crypto.randomUUID(), and passes on thenotifyTypingRPC), hand that same id to the page route as a query parameter, and filter the listener on it:typing.listen({ filter: (p) => p.clientId !== myClientId }). The filter closes over the id and runs on the server, so the user's own pings are never sent to their browser. Server-side filtering saves each browser the pings it would drop, which pays off as the number of typers in a room grows. - Stale typers on disconnect. A user who closes the tab mid-typing leaves
their entry in everyone else's
typersarray for up to 3 seconds. ThesetTimeoutcleans it up regardless; no separate disconnect-detection is required. - Customizing the indicator. Two typers shows "alice, bob typing…". For
"alice and bob", join with
e:ifbranches. For numbers ("3 people typing"), rendertypers.lengthdirectly.