elements
Start Docs Blog Demos UI Pricing
Elements Manual
  • Getting Started
  • CLI
  • Build
  • Browser
  • Packages
  • TypeScript
  • Elements HTML
  • Assets
  • RPC
  • Router
  • Session
  • Database
  • Migrations
  • LiveTable
  • Channel
  • Jobs
  • Email
  • Payments
  • JSON
  • Async
  • Style
  • UI
  • JSOC
  • Config
  • Tests
  • Logs
  • Deploy
  • Editors
  • Recipes
    • Todo App
    • Todo App: Markup and Styles
    • Authentication
    • Form Validation
    • Signup with Email Confirmation
    • Signup Wizard
    • Admin Roles
    • File Upload
    • Serving Assets From the Database
    • Live Comments
    • Likes / Votes Toggle
    • Shared Lists
    • Team-Partitioned Table
    • Chat Rooms
    • Typing Indicator
    • Grouped Feed Without Flicker
    • Unread Counts
    • Room Presence
    • Collaborative Canvas
    • Infinite Scroll Feed
    • Bidirectional Partition
    • Search and Filter
    • Admin Table
    • Markdown Blog
    • Public and Admin Views
    • Cron Cache
    • Live Dashboard
    • Live Updates From Any Write
    • Marketing Page
    • Status Indicators
    • Markdown Editor
    • Time Ago
  • Licenses
  • Issues
  • Changelog
Manual / Recipes/ Todo App

Todo App

elements man recipes/todo-app

On This Page

  • Migration
  • Row types and helpers in models.ts
  • The route
  • Filtering and sorting
  • Adding
  • Updating
  • Renaming inline
  • Deleting, with an animation
  • Empty states
  • Styles and markup
  • A page test
  • Checking live updates in two tabs

A single-page todo list: add, rename inline, check off, star, delete, and filter by All / Active / Done. Every change appears in every open tab without any extra code, because one LiveTable backs the page.

This is the recipe to read first. It is short and it uses the features most apps need: an optimistic insert, a filtered and sorted list that stays live, a filter stored in the URL, partial updates, and a delete that animates.

Migration

Terminal
elements create migration 'add todos' -tables=todos
app/migrations/<timestamp>-add-todos.migration.sql
-- add todos create or replace function touchUpdatedAt() returns trigger language plpgsql as $$ begin new.updatedAt = now(); return new; end; $$; create table todos ( id uuid primary key default uuidGenerateV7(), title text not null, done boolean not null default false, starred boolean not null default false, createdAt timestamptz not null default now(), updatedAt timestamptz not null default now() ); create index todosDoneCreatedAt on todos (done, createdAt desc); create trigger todosTouchUpdatedAt before update on todos for each row execute function touchUpdatedAt();

Row types and helpers in models.ts

This page is large enough to split. The row types and the pure helpers over them go in a models.ts sibling, the route stays in index.ts, and the markup plus its handlers stay in template.ehtml. A smaller page keeps all of it in template.ehtml and imports from ./template where the route needs it.

app/pages/home/models.ts
export interface Todo { id: string; title: string; done: boolean; starred: boolean; createdAt: Date; /** Client-only: the row is playing its leave animation. */ leaving?: boolean; } export type Filter = "all" | "active" | "done"; export interface View { filter: Filter; } export interface Draft { title: string; } /** * The row being renamed, and the text so far. A buffer rather than fields on * the row, so typing never touches the todo. */ export interface Edit { id: string; title: string; } export function matches(todo: Todo, filter: Filter): boolean { if (filter === "active") { return !todo.done; } if (filter === "done") { return todo.done; } return true; } export function byPriority(a: Todo, b: Todo): number { if (a.starred !== b.starred) { return a.starred ? -1 : 1; } return +b.createdAt - +a.createdAt; } export function parseFilter(param: unknown): Filter { return param === "active" || param === "done" ? param : "all"; }

Two practices to copy from this file.

Keep view state off the row where you can. editing and saved fields on a Todo would put a half-typed title on the row itself: a second tab would show it while you are still typing, and cancelling would need a copy of the old title to restore. An Edit object in template state, separate from the table, has neither problem. leaving stays on the row because several rows can be leaving at once, and it sets only a CSS class.

createdAt is a Date on every row. The row insert draws before the server responds has the new Date() you pass, and rows from the server arrive as Date too, so the comparator subtracts them directly.

The route

app/pages/home/index.ts
import { Request, Response, LiveTable } from "@elements/app"; import { parseFilter, Todo } from "./models"; import html from "./template"; /* No ordering here. How the list is arranged on screen is a view concern and lives in the template, in byPriority. */ const todos = new LiveTable<Todo>(); export default function route(req: Request, res: Response) { return new html({ todos: todos.view(), view: { filter: parseFilter(req.query.filter) }, }); }

A LiveTable is always live: an insert here is broadcast to every page watching this table, on every app server. There is nothing to turn on.

The filter is stored in the URL as a query param. GET /?filter=done server-renders with Done already applied, so a reload or a shared link shows the same filter. req.query holds the query string; parseFilter returns all for any value other than active or done.

Filtering and sorting

filter() and sort() return plain arrays, and the loop is still live. The e:for expression iterates the view, so the expression depends on the view's rows: when a row is added or removed, the expression re-runs and the loop matches the new array to the rendered rows by id. The rows that did not change keep their DOM and their state:

app/pages/home/template.ehtml
<ul class="todo-list" e:if={countOf(todos, view.filter) > 0}> <li e:for={todo of todos.filter((todo) => matches(todo, view.filter)).sort(byPriority)} class={["todo-item", todo.done && "is-done", todo.leaving && "is-leaving"]} onanimationend={() => onLeaveEnd(todos, todo)}>

The loop's expression is reactive: it re-runs when anything it read changes, and the predicate reads view.filter, so a tab click re-filters the list. Hoisting the expression into a helper like visible(todos, view.filter) behaves the same way.

Do not render every row and hide some with display: none either. A hidden row is still in the DOM, still bound, and still counted by anything that walks the list.

The tabs are the Tabs template from @elements/ui (elements man ui/templates/tabs). Its value is two-way, so the active tab follows view.filter on a reload or the back button, and onValueChange runs when the user picks one. There is no TabsContent: the one list below is the panel, filtered by the same view.filter. parseFilter turns the tab's string value back into a Filter:

app/pages/home/template.ehtml
<Tabs class="todo-tabs" value={view.filter} onValueChange={(filter) => onFilter(view, parseFilter(filter))}> <TabsList label="Filter"> <TabsTrigger value="all">All <Badge variant="secondary">{countOf(todos, "all")}</Badge></TabsTrigger> <TabsTrigger value="active">Active <Badge variant="secondary">{countOf(todos, "active")}</Badge></TabsTrigger> <TabsTrigger value="done">Done <Badge variant="secondary">{countOf(todos, "done")}</Badge></TabsTrigger> </TabsList> </Tabs>
app/pages/home/template.ehtml
function onFilter(view: View, filter: Filter) { view.filter = filter; history.pushState(null, "", filter === "all" ? "/" : `/?filter=${filter}`); }

The assignment re-renders the list in place; nothing is refetched and the page never reloads. history.pushState then writes the new URL into the address bar and adds a history entry, one per filter change. It rewrites the address bar and nothing more: actual navigation still goes through redirect(url).

The back button moves back through those entries, and the browser raises a popstate event each time. Add the listener in the root's oninit (elements man html/events) and set the filter from the URL, which re-renders exactly as a tab click does:

app/pages/home/template.ehtml
<html class="page-todos" ( todos: LiveView<Todo>, view: View, private draft: Draft = { title: "" }, private edit: Edit = { id: "", title: "", }, ) oninit={() => window.addEventListener("popstate", () => onPopState(view))}>
app/pages/home/template.ehtml
function onPopState(view: View) { view.filter = parseFilter(new URLSearchParams(window.location.search).get("filter")); }

view is an object rather than a bare attribute because the template re-renders when a handler assigns to an object's field, and does not when a handler reassigns a plain attribute (elements man html/attributes).

The counts are computed from the same view:

app/pages/home/template.ehtml
function countOf(todos: LiveView<Todo>, filter: Filter): number { return todos.filter((todo) => matches(todo, filter)).length; }

Adding

app/pages/home/template.ehtml
function onAdd(todos: LiveView<Todo>, draft: Draft) { let title = draft.title.trim(); if (title === "") { return; } /* createdAt is set here even though the column defaults to now(): the optimistic row is painted from exactly this object, and the order depends on it. */ todos.insert({ title, done: false, starred: false, createdAt: new Date(), }, () => draft.title = ""); }

insert draws the new row before the server responds, from the object you pass and nothing else. Any field the template reads goes in it, including ones the database would have filled in. Passing createdAt here places the new row in its final position from the first frame.

The second argument clears the composer. Use it for UI state only, never to navigate: it runs before the write is sent.

Updating

Checkbox and Toggle call their callbacks with the new value, so each handler copies the row with ...todo and sets the one field that changed:

app/pages/home/template.ehtml
function onToggle(todos: LiveView<Todo>, todo: Todo, done: boolean) { todos.update({ ...todo, done, }); } function onStar(todos: LiveView<Todo>, todo: Todo, starred: boolean) { todos.update({ ...todo, starred, }); }

An update patches the row in place, so the row keeps its DOM and only the bindings that read the changed field repaint. Listing every column by hand works too, but then the call does not show which field changed.

Renaming inline

The editor is one Input that replaces the todo's title while edit.id is that todo's id. Its value is bound to edit.title:

app/pages/home/template.ehtml
function onEditKeyDown(e: KeyboardEvent, edit: Edit) { if (e.key === "Enter") { (e.target as HTMLInputElement).blur(); } if (e.key === "Escape") { onCancelEdit(edit); } }
app/pages/home/template.ehtml
<Input class="todo-text" e:if={edit.id === todo.id} value={edit.title} attrs={{ "aria-label": "Edit todo" }} oninsert={(e: LifecycleEvent) => (e.target as HTMLInputElement).select()} onblur={() => onCommit(todos, edit, todo)} onkeydown={(e) => onEditKeyDown(e, edit)} /> <button class="todo-label" e:else type="button" aria-label={`Edit ${todo.title}`} onclick={() => onEdit(edit, todo)}> {todo.title} </button>
app/pages/home/template.ehtml
function onEdit(edit: Edit, todo: Todo) { edit.id = todo.id; edit.title = todo.title; flush(); } function onCommit(todos: LiveView<Todo>, edit: Edit, todo: Todo) { if (edit.id !== todo.id) { return; } edit.id = ""; let title = edit.title.trim(); if (title === "") { onRemove(todos, todo); return; } if (title === todo.title) { return; } todos.update({ ...todo, title, }); } function onCancelEdit(edit: Edit) { edit.id = ""; }

flush() mounts the input synchronously inside the click, which is what lets iOS Safari open the keyboard for it (elements man html/events). oninsert is a lifecycle handler, so it goes on the template tag as it would on an element, and e.target is the <input> the template renders. Cancelling is one assignment because typing changed only edit.title, never the todo.

Deleting, with an animation

app/pages/home/template.ehtml
/* Matches --duration-normal, the css the leave animation runs with. */ const LEAVE_MS = 220; function onRemove(todos: LiveView<Todo>, todo: Todo) { todo.leaving = true; setTimeout(() => todos.delete(todo), LEAVE_MS); } function onLeaveEnd(todos: LiveView<Todo>, todo: Todo) { if (todo.leaving) { todos.delete(todo); } }

Two callbacks call todos.delete(todo), and either may run first. The animationend handler usually runs first. The timer is there for a background tab, where the browser throttles animations and may never raise the event; the delete the user asked for still has to happen.

Whichever arrives second deletes a row that is already gone, and that is a no-op: the table looks the row up by id and returns when it is not there. So neither callback needs a flag tracking the other.

Do not use the timer alone. A busy browser can run a 200ms timer seconds late, and the row stays on screen, faded out, until the timer runs.

Clearing every done row is the same call in a loop:

app/pages/home/template.ehtml
function onClearDone(todos: LiveView<Todo>) { for (let todo of todos.filter((todo) => todo.done)) { onRemove(todos, todo); } }

Empty states

The list has three empty states, because a list with no todos and a filter with no matches need different messages. Empty is the @elements/ui empty-state template, and e:if, e:elseif and e:else choose its title:

app/pages/home/template.ehtml
<Empty e:else> <EmptyHeader> <EmptyTitle e:if={todos.length === 0}>Nothing on the list</EmptyTitle> <EmptyTitle e:elseif={view.filter === "active"}>All caught up</EmptyTitle> <EmptyTitle e:else>Nothing finished yet</EmptyTitle> </EmptyHeader> </Empty>

Styles and markup

The complete markup and style.css are in todo-app-markup (opens in a new tab): the @elements/ui templates for the card, composer, tabs, badges, rows, empty state and footer, and the tokens that space and color them, light and dark. Copy them rather than writing your own.

Change colour first and layout second, and delete the scaffolded markup before you touch layout. See start/patterns for why: a page that is half old markup and half new CSS looks broken while you work, and if anyone is watching, that is what they see.

A page test

A test renders the page with toHtml() and checks the result (elements man tests/pages). The rows it inserts roll back when it ends:

app/pages/home/test.ts
import { test, assert, sql, LiveTable } from "@elements/app"; import { Todo } from "./models"; import html from "./template"; const todos = new LiveTable<Todo>(); test("home", () => { test("starred rows come first", () => { sql(` insert into todos (title, starred) values ('Book the dentist', false), ('Water the plants', true) `); let page = new html({ todos: todos.view(), view: { filter: "all" }, }).toHtml(); assert(page.indexOf("Water the plants") < page.indexOf("Book the dentist"), "starred is not first"); }); });

The pure helpers in models.ts are tested by calling them, with no page at all.

Checking live updates in two tabs

The build checks that the code compiles. To check the live updates, open two tabs on http://localhost:4000/ and confirm each of these:

  • Adding a todo in one tab makes it appear in the other.
  • Checking one row repaints that row alone; livetable explains how the loop leaves the other rows' DOM unchanged.
  • Deleting a row in the middle removes that row and no other, and leaves no faded row behind.
  • Active hides a row the moment you check it, and Done shows it.
  • Reloading /?filter=done opens on Done, a tab click rewrites the URL with no reload, and the back button steps through the filters you clicked.
  • Renaming a row and pressing Escape leaves the original title.
Prev RecipesNext Todo App: Markup and Styles
Product
Manual Pricing Compare
Company
History Contact
Legal
Privacy Policy Acceptable Use Terms License Agreement
© Elements Dev Corporation 2026