Conventions
elements man start/conventionsHow Elements differs from other web frameworks, from project structure to styling, 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 go 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 be written in a shared layout template. - A site's header, nav and footer are written in one layout template with the
<main>, all on onepage-shellwidth. In a site with that shared layout, 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. An app of one page with no shared header putspage-shelland its width on its own<main>. See Layout (opens in a new tab). - Template attributes are declared on a template's 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 keys each item by 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. A value set with
el.value = "..."is not copied to the bound variable; bind withvalue={form.x}and assignform.xinstead. Use{raw(html)}for unescaped HTML rather thanel.innerHTML. - Mutating an object's fields in a handler updates the template. Reassigning a
variable does 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"]}. That is for an HTML element. Theclassattribute of a template from@elements/ui, such as<Icon>, is a string. - 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 function in the event attribute passes template attributes to the handler. <form onsubmit={...}>callse.preventDefault()itself.- 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 themselves. - 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 changes and the template re-renders beforeredirect()runs. Redirect a signed-in visitor from the route instead.
RPC and Errors
- Code inside an
@rpcfunction runs on the server. It, and every function it calls, can callsql(),tx(), andsession. - One form object per
@rpc, with itsFile[]fields on that same object. - Internal errors are wrapped in
ServerErrorbefore they are sent to 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 it to snake_case for Postgres, and snake_case still works if you prefer it.
- In development, editing an applied migration re-runs it against the local database. On a deploy machine each migration runs once.
LiveTable
- A LiveTable is always live. A page that needs rows once, with no
subscription, calls an
@rpcthat returns them fromsql. insert(...)shows the row in the browser at once, before the server answers, and it renders only the object you pass. 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 server's broadcast of the saved row arrives.- 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 Code
- 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. Do not writeasyncorawaiton those calls yourself: the compiler adds them. - 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. ExtendingJobis what registers it: there is noapp.job(...)call and no build 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 inserts every row any test in the file needs makes every test use the same rows, so the tests wait on each other's row locks, and a change to any part of the fixture 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.
Source Code 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 go out of date as code moves.
- The code must be human readable. Never write long single-line code. 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 be written 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 is directly 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 `);