Shared Lists
elements man recipes/shared-listsA todo list whose id is part of its URL. Two browsers on the same /lists/:id see
each other's edits in real time as items are added, toggled, or removed. The
shared id is the only piece of "access control"; anyone with the URL can read
and edit.
Two LiveTables drive the recipe. lists holds the lists themselves and is used
on the home page. listItems is opened per list with view({ listId }), so a
mutation on one list only broadcasts to browsers watching that list.
Migration
Terminalelements create migration 'add lists' -tables=lists,listItems
app/migrations/<timestamp>-add-lists.migration.sql-- add lists -- 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 lists ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), title text not null ); create trigger listsTouchUpdatedAt before update on lists for each row execute function touchUpdatedAt(); create table listItems ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), listId uuid not null references lists(id) on delete cascade, text text not null, done boolean not null default false ); create trigger listItemsTouchUpdatedAt before update on listItems for each row execute function touchUpdatedAt();
listItems.listId is the partition column: listItems.view({ listId }) receives
only the items whose listId matches. The on delete cascade foreign key cleans up items
when a list is deleted.
LiveTables
The LiveTables are declared in app/shared/services/lists.ts so both pages can
import them.
app/shared/services/lists.tsimport { LiveTable } from "@elements/app"; export interface List { id: string; createdAt: Date; title: string; } export interface ListItem { id: string; createdAt: Date; listId: string; text: string; done: boolean; } export let lists = new LiveTable<List>(); export let listItems = new LiveTable<ListItem>();
No insert, update, or delete handlers. Anyone with the URL may
edit, so each mutator runs the auto-SQL (one statement against the table) with
no check. To gate by
ownership, add handlers; see elements man livetable.
Home page
Terminalelements create page home
The home page renders every list with a link to its URL, and a form to create a
new list. Creating a list returns its id; the handler navigates to /lists/:id
so the new list opens immediately.
app/pages/home/services.tsimport { sql } from "@elements/app"; /** @rpc */ export function createList(title: string): string { return sql<{ id: string }>( ` insert into lists ( title ) values ( ${title} ) returning id `, ).firstOrThrow().id; }
app/pages/home/index.tsimport { Request, Response } from "@elements/app"; import home from "./template"; import { lists } from "#app/shared/services/lists"; export default function route(req: Request, res: Response) { return new home({ lists: lists.view() }); }
app/pages/home/template.ehtmlimport "./style.css"; import { LiveView, redirect } from "@elements/app"; import { Button } from "@elements/ui/button"; import { Input } from "@elements/ui/input"; import { List } from "#app/shared/services/lists"; import { createList } from "./services"; function onSubmit(title: string) { let id = createList(title); redirect(`/lists/${id}`); } <html class="page-home" ( lists: LiveView<List>, private title: string = "", )> <main class="page-shell"> <h1>your lists</h1> <ul class="lists"> <li e:for={l of lists.sort((a, b) => +b.createdAt - +a.createdAt)}> <a href={`/lists/${l.id}`}>{l.title}</a> </li> </ul> <form class="row" onsubmit={() => onSubmit(title)}> <Input value={title} placeholder="new list title" required /> <Button variant="primary" type="submit">create</Button> </form> </main> </html>
The home page receives a view of the whole lists table from the route.
Inserts from any browser appear in the list immediately. The local title is
reactive state for the Input, whose value is two-way. The Button says
type="submit" because a button template is type="button" unless told
otherwise.
List page
Terminalelements create page list
The list page loads the list's title from the database (a one-time read, not live) and passes the list's partition of items to the template.
app/pages/list/index.tsimport { Request, Response, sql } from "@elements/app"; import list from "./template"; import { List, listItems } from "#app/shared/services/lists"; export default function route(req: Request, res: Response) { let row = sql<List>(` select id, createdAt, title from lists where id = ${req.params.id} `).firstOrThrow("list not found"); return new list({ list: row, items: listItems.view({ listId: row.id }), }); }
firstOrThrow("list not found") throws NotFoundError (a safe 404) with the
given message if no row matches. The message reaches the browser as the body of
the response.
app/pages/list/template.ehtmlimport "./style.css"; import { LiveView } from "@elements/app"; import { Button } from "@elements/ui/button"; import { Checkbox } from "@elements/ui/checkbox"; import { Icon } from "@elements/ui/icon"; import { Input } from "@elements/ui/input"; import { List, ListItem } from "#app/shared/services/lists"; function onSubmit(items: LiveView<ListItem>, draft: { value: string }) { items.insert({ text: draft.value, done: false, }, () => draft.value = ""); } function onToggle(items: LiveView<ListItem>, item: ListItem, done: boolean) { items.update({ ...item, done, }); } function onRemove(items: LiveView<ListItem>, item: ListItem) { items.delete(item); } <html class="page-list" ( list: List, items: LiveView<ListItem>, private draft: { value: string } = { value: "" }, )> <main class="page-shell"> <h1>{list.title}</h1> <ul class="items"> <li e:for={item of items.sort((a, b) => +a.createdAt - +b.createdAt)} class={["row", item.done && "done"]}> <Checkbox checked={item.done} attrs={{ "aria-label": `Done: ${item.text}` }} onCheckedChange={(done) => onToggle(items, item, done)} /> <span class="text">{item.text}</span> <Button variant="ghost" size="sm" icon label={`Remove ${item.text}`} onclick={() => onRemove(items, item)}> <Icon name="x" /> </Button> </li> </ul> <form class="row" onsubmit={() => onSubmit(items, draft)}> <Input value={draft.value} placeholder="add an item" required /> <Button variant="primary" type="submit">add</Button> </form> </main> </html>
items.insert(...) adds the row to the page at once, before the server
confirms the write. The view fills listId from its partition, so the call
passes only text and done. The second argument is the resetUI callback:
it clears the input as soon as the row is added locally. The Checkbox calls
onCheckedChange with the new value, and items.update({ ...item, done }) and
items.delete(item) are calls on the view, so each change is broadcast. Every
browser with listItems.view({ listId }) open for this list updates the
affected row in place.
draft is wrapped in { value: ... } because the handler receives it as a
function parameter. Assigning draft.value = "" changes a field of the object
the template also holds, so the template renders the new value. Assigning to a
plain string parameter changes only the function's local variable.
Routes
Register the pages in index.ts:
index.tsimport home from "#app/pages/home"; import list from "#app/pages/list"; // ... app.route("/", home); app.route("/lists/:id", list);
Notes
- Open access. With no handlers on the LiveTables and no guard in
either route, the only thing keeping a list private is the secrecy of its
uuidv7 id. uuidv7 has 122 bits of entropy, so the id is effectively
unguessable, but anyone you share the URL with can read and edit. To require
login, wrap each route with
session.isLoggedInOrThrow()and add handlers to the LiveTables that call it too. - Per-list ownership. Add an
ownerIdcolumn tolists, then inupdateanddeletehandlers onlistItemscallsession.isLoggedInOrThrow(), look the owner up, and throwForbiddenErrorwhen it is notsession.getOrThrow('userId'), for "anyone can read, only the owner can edit". The partition still decides which items each browser receives, so each browser receives only the items of the list it has open. - Deleting a list. The
on delete cascadeforeign key onlistItems.listIdremoves a list's items automatically when the list is deleted. Use thelistsview'sdeletemutator from a "delete list" button on the home page. - Cross-tab sync. A user with the same list open in two tabs sees both tabs update. The LiveTable broadcasts each change to every open view of the list, whether the view is in the same user's other tab or in another user's browser, on every app server.
- The
listsLiveTable on/lists/:id. This recipe only passeslistItems.view({ listId })to the list page. To also show "your other lists" in a sidebar on the list page, passlists.view()along too. Both views coexist without interference. - Writes from jobs and psql. Add the trigger from
elements man recipes live-from-sqland an item inserted by a job, an@rpcusingsql, or psql goes live on every open list too.