Conventions
elements man start/conventionsWhere Elements differs from what you would guess from the outside, and the conventions its own source follows. Read this once before you write a first page and the rest of the manual reads faster.
Project structure
- Routes are declared in
index.ts, not file-based. Folder names underapp/pages/are labels, not URLs. - A scaffolded page has
index.ts(route only) andtemplate.ehtml(template, event handlers, inline RPC). As a page grows, move its@rpcfunctions and shared interfaces into a hand-authoredservices.tssibling. An@rpcnever belongs in a page'sindex.ts. - Scaffold with
elements createand treat the scaffold as a guide: fill it in, and do not discard its parts without a good reason. - Cross-page services and templates live under
app/shared/. - Import app source with the
#app/...map (#app/pages/...,#app/shared/...), never../../.#configimports config. - Import a page's template extensionless:
import html from "./template". - Use kebab-case for directories and filenames.
HTML templates
- TypeScript goes outside template declarations or inside
{}expressions, not in<script>tags. A<script>or<style>body evaluates{}like any other element, ande:literalkeeps a body as written. - Group siblings that share a condition in an ordinary element, such as a
<div>. A browser keeps a<template>element's content off the page, so Elements groups with rendered elements. - Every page has one
<main>around its primary content. Screen readers use it to skip past navigation and headers. It can live in a shared layout template. - A site's header, nav and footer live in one layout template with the
<main>, all on onepage-shellwidth. A page never sets its own shell width, or the header moves from page to page. A narrower page narrows its content withmax-w-2xlormax-w-prose. See Layout (opens in a new tab). - Attributes live on the root tag only.
<div (form: Form)>inside a template is invalid. <html>is the default-export page andhtmlis a reserved name. Other top-level tags are named templates.e:forkeys by theidfield. Provide one or the runtime warns and falls back to object identity.- The directives are
e:for,e:if/e:elseif/e:else, ande:switch/e:case/e:default. - Read and write data, not the DOM.
el.value = "..."fights the runtime; bind withvalue={form.x}instead. Use{raw(html)}for unescaped HTML rather thanel.innerHTML. - Mutating an object's fields in a handler is live. Rebinding is not: a function
cannot reassign its caller's variable, so
errors = serverErrorsinside a handler does nothing. Assign in template scope (onsubmit={() => errors = submit(form)}) or wrap a scalar in{ value }. - Class arrays drop falsy entries:
class={["card", active && "active"]}. - The lifecycle hooks are
oninit,oninsert, andonremove. Each receives an event object withevent.targetset to the element. - Event handlers are named functions in the same
.ehtmlfile. The inline arrow passes template attributes into one. <form onsubmit={...}>callse.preventDefault()for you.- Give every form control a
name:<input name="email" value={form.email}>. A binding does not name it, so an unnamed control is left out of a submit.groupbindings are the exception and name their radios for you. - Navigate with
redirect(url), notwindow.location. The same call works in a template handler, a route, middleware, and an@rpc. Do not render asession.isLoggedIn()view on a signin page: login is an@rpc, so the session flips and repaints beforeredirect()runs. Bounce a signed-in visitor from the route instead.
RPC and errors
@rpcis the boundary. Once across it, anything downstream can callsql(),tx(), andsessionfreely.- One form object per
@rpc, with itsFile[]fields on that same object. - Internal errors are wrapped in
ServerErrorbefore they reach the client. Throw anAppErrorsubclass for a message the client should see. ValidationError(message)covers a single rule andValidationError(fieldErrors)a per-field map. In a template, direct-assign the result:errors = err.errors, notObject.assign.- There is no
validate()in@elements/app. ThrowValidationError.
Database
sql(),tx(),session.login(), andsession.logout()are server-only. Browser code, event handlers and template expressions included, cannot call them: the compiler reports a security error at the call site. Call an@rpcfunction, and put the server-only call inside it.${value}interpolations are parameterized, so SQL injection is impossible by construction.sql<T>(...)returns aSqlResult<T>..all()gives the array,.first()givesT | undefined, and.firstOrThrow(msg)gives a required row.- Nesting
tx()joins the transaction already in progress, and innersql()calls join the outer transaction automatically. - Write camelCase in SQL. Elements translates at the database boundary, and snake_case still works if you prefer it.
- Migrations are hot in development and frozen in production.
LiveTable
- A LiveTable is always live. A page that wants rows once, with no
subscription, calls an
@rpcthat returns them fromsql. - An optimistic
insert(...)paints only the object you pass, so include every field the template reads. Server-generated columns count: timestamps, sequence numbers, and trigger-derived values do not exist client-side yet, so pass a placeholder such ascreatedAt: new Date(). Omit a displayedcreatedAtand the cell rendersInvalid Dateuntil the broadcast lands. - A LiveView is an iterable.
filter,sort,map,find,at, andlengthare the Array methods over a copy of its rows and return plain arrays. A helper that builds its own array from the view is live in ane:fortoo. - Never redirect from a mutation's
resetUI. It runs before the write is sent and the row is lost. Redirect after a syncinsert(), or use a plain@rpc.
Sync-style
- The Elements functions that support it (
sql,tx, RPC calls and the rest listed inman async) are written sync-style, and the compiler propagatesasync/awaitup the call stack. Writing them by hand on those calls fights the transform. - For third-party libraries (fetch, Stripe,
navigator.clipboard), declare your functionasyncandawaitthose calls directly. Your ownasync/awaitis left alone. - The
xAsyncvariants (sqlAsync,txAsync,insertAsync) are for promise control such asPromise.allover several calls. A sync-style write persists once sent; navigate on the line after it.
Session
- Read session values with
session.get("userId")orsession.getOrThrow("userId")and type them through theSessionDatainterface. There is nogetUserId(). - A logged-out visitor has no session: no row, no token, no cookie.
- A template that reads a session method updates when the session changes.
Jobs
- A job is a class that extends
Job. Nothing else registers it: there is noapp.job(...)and no tag to write. - Suffix job class names with
Job, as inSendWelcomeJob.
Tests
- A test reads top to bottom: create the rows it needs, call the code, check the result. Name it for what the code does, in plain words, not for the requirement it satisfies.
- Each test creates what it needs and nothing more. A fixture that builds the whole world ties every test in the file to the same rows, so they wait on each other's locks, and a change to any part of it fails them all.
- Helpers are named functions with typed parameters and a return type, laid out like the tests that call them.
Styling
- Bare elements are already styled. A
<button>is a finished button, and so is an<input type="submit">. Inputs, forms, headings, links, tables, and<code>need no classes. - Vary a button with
is-modifiers rather than a new class:is-primary/is-ghost/is-danger,is-sm/is-lg,is-block. Render an<a>as a button withclass="button is-primary". - Setting padding, border, radius, or background on something the design system
already styles means rebuilding what exists. Read
elements man styleand use the class. - Custom CSS is for layout the system does not provide: page composition, positioning, section spacing.
- Text is
--ink,--ink-softor--ink-dim.--ink-faintis for placeholders and decoration: as text it fails contrast, and a page using it scores under 100 on Lighthouse accessibility.
Conventions
- Always use semicolons in TypeScript and JavaScript.
- A comment says why, never what the next line already says. No banner comments grouping code, and no boxed dividers or ascii rules. They add noise and rot as code moves.
- The code must be human readable. Write it for the person who reads it next: one statement per line, a blank line between steps. Code compressed onto a few long lines compiles the same and costs the reader every time the file is opened.
- Never minify or compress source to save space or tokens. Generated files and data files are the only exception.
- Lines are at most 100 characters. Only a string literal, a SQL template literal or data may run longer.
- Every block has braces and its body on its own indented lines, even a single
statement. No
if (done) return;and no one-line{ ... }body. An object or array literal with three entries or fewer may sit on one line:
Blocksif (!user) { return; } const origin = { x: 0, y: 0 };
- One variable per declaration. Write
const a = 1, b = 2as two lines. - A ternary picks between two plain values. Never nest one, and never put
logic in its branches: use
if. - Keep functions short, around 50 lines, and return early rather than nesting.
- Names say what a thing is. Single letters are for loop indexes only.
- Template HTML is multiline and indented, one element per line. An element with more than three attributes puts one attribute per line:
Template layout<ul class="posts"> <li e:for={post of posts}> <a href={post.url}>{post.title}</a> </li> </ul> <input type="email" name="email" value={form.email} required >
- A template expression is a call or a property read, as in
{post.title}or{formatDate(post.createdAt)}. Logic moves into a function in the same file. - CSS puts one selector per line and one declaration per line:
Rule layout.post-title, .post-meta { margin: 0; color: var(--ink-soft); }
- Type the rows you read,
sql<Row>(...), and the values you pass.anyhides the mistakes the compiler exists to catch. - Environment names are an open set: any name works, with its own
config/env/<name>.envanddeploy.env.<name>block.ENVdefaults todevelopmentlocally, andelements deploydefaults toproduction. Code that depends on where the app runs branches onisDeployMachine(), never on the environment name. - Write every
insertthe same way, whatever the number of columns: each column on its own line,) values (on one line, then each value on its own line in the same order, so the nth value sits under the nth column:
Insert layoutsql(` insert into signups ( name, email, fileName ) values ( ${name}, ${email}, ${file?.name} ) `);
- Lay out
select,updateanddeleteby clause:select,from, eachjoin,where,group by,order by,limit,setandreturningeach start a line. A clause with several columns, conditions or assignments puts its keyword alone on the line and one item per line under it, with further conditions leading withandoror. A clause with one item stays on its keyword line. Only a bareselect ... from <table>stays on one line:
Query layoutsql(` select id, name from users where active = ${true} and orgId = ${orgId} order by createdAt desc `);