Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,16 @@ These are the rules that must not be forgotten or looked up — they're the ones
- Props that query the database, read storage, or do expensive work must be zero-argument functions (`assign_prop(conn, :items, fn -> ... end)`) so partial reloads skip excluded work. Keep authentication and authorization outside these callbacks so they run on every request. Inertia must stay on 3.1 or newer; 3.0.1 evaluates excluded callbacks.
- Page components are **always** `.tsx` (TypeScript), under `assets/js/pages/` in one of two strategy dirs: **`pages/ssr/`** (server-rendered: public / SEO / first-paint pages) or **`pages/client/`** (client-only: authenticated, interactive, heavy pages — kept out of the Node SSR bundle). The strategy dir is stripped from the Inertia page name, so `render_inertia("Dashboard")` maps to `pages/client/Dashboard.tsx`. The `_pages.ts` / `_ssr_pages.ts` registries are auto-generated from these dirs by `build/generate-ssr-pages.cjs` — never edit them by hand. New public page → `ssr/`; new authed page → `client/`
- Layout components live in `assets/js/layouts/` (e.g. `AppLayout`, `AuthLayout`)
- Reusable UI primitives live flat in `assets/js/components/` (`Button`, `Spinner`, `Select`, `DropdownMenu`, `AlertDialog`, …) — no sub-folders
- Forms use Inertia's `useForm` hook; errors come from `assign_errors(conn, changeset)` on the server
- Reusable UI primitives live flat in `assets/js/components/` (`Button`, `TextField`, `Spinner`, `Select`, `DropdownMenu`, `AlertDialog`, …) — no sub-folders
- Forms use Inertia's `useForm` hook; errors come from `assign_errors(conn, changeset)` on the server. Text inputs are `TextField` (`error={errors.<field>}`), never a raw `<input>` in pages or layouts
- **No raw `try/catch` for application async work — wrap every Promise in `go()` from `assets/js/result.ts`** (sync work uses `goSync`). It returns an error-first tuple, `[error, value]`, which forces every call site to acknowledge the failure path explicitly and prevents the "swallow the error and move on" pattern that hides real bugs. The same applies to dynamic `import()`, `fetch()`, JSON parsing, and vendor SDK calls. Raw catches are limited to `result.ts`'s own implementation, React error boundaries, and CommonJS build-tool process boundaries that cannot import the TypeScript utility without a runtime transpiler
- **Don't inline a multi-line function into `go(...)` / `goSync(...)`** — extract it to a named function above the call and pass it by name (`const [error, value] = await go(renderApp)`), so the call site stays a scannable one-liner. Small one-line callbacks (`go(() => i18n.changeLanguage(locale))`) are fine to inline. Mirrors the Elixir `with`-clause rule below
- **Multi-line arrow/function bodies use explicit braces and `return`** — never a multi-line implicit return (it's too easy to lose track of what's returned, or drop the `return` when editing, and get weird behaviour). When you convert an implicit return to a block body, **keep the `return`** so the returned value is preserved — only drop it when the value is genuinely unused. And if the body fits on one line within the 120-col width, prefer collapsing to a single-line implicit return rather than a block. Single-line implicit returns (`(x) => x.id`) and idiomatic multi-line JSX render-props wrapped in parens (`({ Component }) => ( <Foo /> )`) are fine
- Never edit `assets/js/_pages.ts`, `assets/js/_ssr_pages.ts`, or `assets/js/routes.ts` — they're auto-generated
- **Frontend paths come from the `routes` helper, never string literals.** `assets/js/routes.ts` is generated from the Phoenix router by `mix routes.gen` (run in `assets.build`/`assets.deploy` + the dev watcher; `mix routes.gen --check` in `precommit` fails the build on drift). Use `routes.login()`, `routes.settingsEmail()`, etc. for every internal URL on the frontend (`<Link href>`, `useForm().post(...)`, `router.visit/delete(...)`) — the TS path-builder is the frontend counterpart to the server's `~p` sigil and keeps the two in sync. Names are the camelCased path (`/settings/email/apply-change` → `settingsEmailApplyChange`, `/` → `root`); `:param` segments become typed args and every builder takes an optional query object (`routes.confirmEmail({ token })`). Adding/removing a route + rebuilding regenerates the file; never hand-edit it
- **Validation errors must redirect, not re-render.** On `{:error, changeset}` always use `conn |> assign_errors(changeset) |> redirect(to: ~p"/current-page")`. Do **not** use `put_status(:unprocessable_entity) |> render_inertia(...)` — Inertia updates the browser URL to the POST/PUT target when you re-render, which is both wrong UX and a regression risk. The Inertia plug flashes errors through the session across the redirect, so the form still shows them
- Use the `~p"/..."` sigil (verified routes) for every internal URL — in controllers, tests, and anywhere else in Elixir. Never write raw route strings; compile-time verification catches typos and broken links
- **JSON serialisation goes through `*_json.ex` view modules**, never ad-hoc serializer modules (no `*Props`, `*Serializer`, or per-controller helpers). One module per resource at `lib/elixir_react_starter_web/controllers/<resource>_json.ex` (e.g. `ElixirReactStarterWeb.PostJSON`) exposes `index/1` and `show/1` (the Phoenix 1.8 equivalents of `render_many`/`render_one`) that both delegate to a single `data/2`. Inertia callers use `MyJSON.data(record, viewer)` directly inside `assign_prop`; JSON API endpoints use `index`/`show` via `render`. This keeps the wire shape for a resource in one place so multiple callers can't drift
- **JSON serialisation goes through `*_json.ex` view modules**, never ad-hoc serializer modules (no `*Props`, `*Serializer`, or per-controller helpers). One module per resource at `lib/elixir_react_starter_web/controllers/<resource>_json.ex` (e.g. `ElixirReactStarterWeb.PostJSON`) exposes `data/1` (or `data/2` with a viewer), used directly inside `assign_prop`; add `index/1`/`show/1` delegating to it once a JSON endpoint renders the resource (see `UserJSON`). This keeps the wire shape for a resource in one place so multiple callers can't drift

**Accessibility (non-negotiable)**
- Every interactive component must support full keyboard navigation, visible focus (`focus-visible` rings), proper ARIA roles/state, and screen-reader labels. No exceptions
Expand All @@ -62,6 +62,7 @@ These are the rules that must not be forgotten or looked up — they're the ones
- Cross-agent review is **on demand**: `wt review-claude` or `wt review-codex` reviews the current worktree; append a branch to review another. Pause edits in the reviewed worktree until it finishes
- **To see a worktree's changes, run `scripts/preview` in it** (in the background): its own server on its own port, beside :4000, which it prints. It shares the dev database, runs its Oban jobs inline on its own code (nothing taken from :4000) and never migrates. Stop your own preview when done; never stop someone else's
- **Browser specs go through `scripts/e2e <spec>`**, never against :4000. It starts its own server on a free port with its own database (`elixir_react_starter_e2e_<branch>`), runs the named specs and stops it. Run only the specs for the flow you changed; CI runs the whole suite
- Concept owners and the architecture rules the tests enforce: `docs/architecture.md`
- Run `mix precommit` when done; fix anything it flags
- Never add a `Co-Authored-By` line to commit messages

Expand Down Expand Up @@ -129,8 +130,8 @@ The template already includes these — extend them, don't rebuild them.
**Realtime** (`ElixirReactStarterWeb.{UserSocket, GlobalChannel, UserChannel}` + `assets/js/realtime/`)
- Token-authed socket at `/socket`. The provider (mounted in `app-providers.tsx`) auto-joins `global` and `user:<id>` and survives Inertia navigation (keyed on user id, not the rotating token). Hooks: `useConnectionStatus`, `useGlobalChannel`, `useUserChannel`, `useChannel`, `use{Global,User}Event`, `pushChannel`

**Locale** (`ElixirReactStarterWeb.LocaleController`, `PUT /locale`)
- Precedence: `user.locale` (authed) → `locale` cookie (anonymous, 1-year) → `Accept-Language` → `:default_locale`. The public endpoint sets the cookie and, when signed in, also writes `user.locale`. Frontend strings go through `react-i18next` (`useTranslation`); locale files are `assets/js/i18n/locales/{en,es}.ts`
**Locale** (`ElixirReactStarter.Locale` for supported/default, `Plugs.Locale` for resolution + cookie, `LocaleController` at `PUT /locale`)
- Precedence `user.locale` (authed) → `locale` cookie (anonymous, 1-year) → `Accept-Language` → default. The public endpoint sets the cookie and, when signed in, also writes `user.locale`. Frontend strings go through `react-i18next` (`useTranslation`); locale files are `assets/js/i18n/locales/{en,es}.ts`

**Theme** (`assets/js/theme.ts`, `ThemeToggle`)
- light / dark / system, stored in a `theme` cookie. An inline bootstrap in `root.html.heex` applies the `dark` class before first paint (no flash). Dark mode is class-based (`@custom-variant dark`)
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@ docker run -p 4000:4000 \
`config/runtime.exs` requires `DATABASE_URL`, `MAILJET_API_KEY`, `MAILJET_SECRET`,
and `SECRET_KEY_BASE` and will refuse to boot without them. `PHX_HOST` defaults to
`example.com` but should always be set in production (it's used for absolute URLs
in emails). `PORT` (default `4000`), `POOL_SIZE`, `ECTO_IPV6`,
in emails). The email sender is the `:mail_from` config value in `config/config.exs`
(`{name, address}`); set it per project, or per environment in that environment's config file. `PORT` (default `4000`), `POOL_SIZE`, `ECTO_IPV6`,
`DNS_CLUSTER_QUERY`, `TRUST_PROXY_HEADERS`, `TRUSTED_PROXIES`,
`CLIENT_IP_HEADERS`, `SSR_POOL_SIZE`
(number of Inertia SSR Node workers, default `2`), and `NODE_OPTIONS` (set in the
Expand Down
25 changes: 24 additions & 1 deletion assets/biome.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,9 @@
"@inertiajs/react": {
"importNames": ["Link"],
"message": "Import Link from components/Link so prefetch is enabled by default."
}
},
"@heroicons/react": "Use lucide-react; heroicons is unmaintained.",
"@radix-ui/themes": "Conflicts with the Tailwind design system. Wrap a @radix-ui/react-* primitive instead."
}
}
},
Expand Down Expand Up @@ -183,6 +185,27 @@
}
}
},
{
// Pages and layouts build form fields with components/TextField, which
// wires the label, error message and ARIA attributes together.
"includes": ["js/pages/**", "js/layouts/**"],
"linter": {
"rules": {
"correctness": {
"noRestrictedElements": {
"level": "error",
"options": {
"elements": {
"input": "Use components/TextField.",
"label": "Use components/TextField.",
"textarea": "Add a field component to components/ and use that."
}
}
}
}
}
}
},
{
"includes": ["e2e/tests/**/*.ts"],
"linter": {
Expand Down
51 changes: 51 additions & 0 deletions assets/build/watch-generated.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
'use strict';
// Dev watcher for the generated frontend files. Regenerates each one when its
// source changes, so neither can go stale while the dev server runs:
//
// * js/_pages.ts + js/_ssr_pages.ts ← js/pages/**/*.tsx (generate-ssr-pages.cjs)
// * js/routes.ts ← the Phoenix router (`mix routes.gen`)
//
// Both run the exact generator that assets.build and precommit use, so each
// generated file keeps one source of truth. Router edits are rare, so booting
// a second BEAM for `mix routes.gen` on change is an acceptable cost.

const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');

const ROOT = path.join(__dirname, '..', '..');

const generators = [
{
watch: path.join(__dirname, '..', 'js', 'pages'),
recursive: true,
relevant: (filename) => filename?.endsWith('.tsx'),
run: () => execFileSync(process.execPath, [path.join(__dirname, 'generate-ssr-pages.cjs')], { stdio: 'inherit' }),
},
{
watch: path.join(ROOT, 'lib', 'elixir_react_starter_web', 'router.ex'),
recursive: false,
relevant: () => true,
run: () => execFileSync('mix', ['routes.gen'], { cwd: ROOT, stdio: 'inherit' }),
},
];

function regenerate(generator) {
try {
generator.run();
} catch {
// The generator already printed its error; keep watching.
}
}

for (const generator of generators) {
regenerate(generator);
fs.watch(generator.watch, { recursive: generator.recursive }, (_event, filename) => {
if (generator.relevant(filename)) {
regenerate(generator);
}
});
}

// Keep the process alive for as long as Phoenix runs the watcher.
process.stdin.resume();
31 changes: 0 additions & 31 deletions assets/build/watch-routes.cjs

This file was deleted.

31 changes: 0 additions & 31 deletions assets/build/watch-ssr-pages.cjs

This file was deleted.

2 changes: 1 addition & 1 deletion assets/js/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import { createRoot, hydrateRoot } from 'react-dom/client';
import pages, { serverRenderedPages } from './_pages';
import { AppProviders } from './app-providers';
import ErrorBoundary from './components/ErrorBoundary';
import { syncLocale } from './components/syncLocale';
import Toaster from './components/Toaster';
import { toast } from './components/toast';
import { syncLocale } from './i18n/syncLocale';
import { go } from './result';
import { startThemeWatcher } from './theme';
import type { Flash } from './types';
Expand Down
37 changes: 37 additions & 0 deletions assets/js/architecture.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Frontend rules from AGENTS.md that no Biome rule can express. Rules Biome
// can express live in biome.jsonc instead (restricted elements and imports).
import assert from 'node:assert/strict';
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import test from 'node:test';

const jsDir = import.meta.dirname;

// Generated files, and the one module allowed to catch (it implements go/goSync).
const excluded = new Set(['routes.ts', '_pages.ts', '_ssr_pages.ts', 'result.ts']);

const sources = readdirSync(jsDir, { recursive: true, encoding: 'utf8' })
.filter((file) => /\.tsx?$/u.test(file) && !file.endsWith('.test.ts') && !file.endsWith('.d.ts'))
.filter((file) => !excluded.has(file))
.map((file) => ({ file, code: stripComments(readFileSync(join(jsDir, file), 'utf8')) }));

function stripComments(source: string): string {
return source.replace(/\/\*[\s\S]*?\*\//gu, '').replace(/(?<lead>^|\s)\/\/.*$/gmu, '$<lead>');
}

function offenders(pattern: RegExp): string[] {
return sources.filter(({ code }) => pattern.test(code)).map(({ file }) => file);
}

test('the rules scan real source files', () => {
assert.ok(sources.length > 10, `only ${sources.length} files found under ${jsDir}`);
});

test('async failures go through go()/goSync(), never a raw try/catch', () => {
assert.deepEqual(offenders(/\btry\s*\{|\.catch\(/u), [], 'wrap the call in go() or goSync() from result.ts');
});

test('internal URLs come from the routes helper, never a string literal', () => {
const literalPath = /\b(?:href|action)=\{?\s*['"`]\/|\b(?:visit|get|post|put|patch|delete|reload|fetch)\(\s*['"`]\//u;
assert.deepEqual(offenders(literalPath), [], 'use routes.<name>() from routes.ts');
});
20 changes: 5 additions & 15 deletions assets/js/components/LocaleSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { router, usePage } from '@inertiajs/react';
import { Check } from 'lucide-react';
import { Check, ChevronDown } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { routes } from '../routes';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from './DropdownMenu';

Expand All @@ -13,6 +14,7 @@ const locales = [
];

export default function LocaleSelector({ className = '' }: LocaleSelectorProps) {
const { t } = useTranslation();
const { locale } = usePage().props;
const current = locales.find((l) => l.code === locale) || locales[0];

Expand All @@ -32,11 +34,11 @@ export default function LocaleSelector({ className = '' }: LocaleSelectorProps)
return (
<DropdownMenu>
<DropdownMenuTrigger
aria-label="Change language"
aria-label={t('common.changeLanguage')}
className={`focus-visible:outline-primary flex cursor-pointer items-center gap-1.5 rounded px-1.5 py-1 text-sm focus-visible:outline-2 focus-visible:outline-offset-2 ${className}`}
>
<current.flag className="h-4 w-5 rounded-sm" />
<ChevronDown className="size-3.5" />
<ChevronDown className="size-3.5" aria-hidden="true" />
</DropdownMenuTrigger>
<DropdownMenuContent className="w-40">
{locales.map(({ code, label, flag: Flag }) => (
Expand Down Expand Up @@ -81,15 +83,3 @@ function FlagES({ className }: { className?: string }) {
</svg>
);
}

function ChevronDown({ className }: { className?: string }) {
return (
<svg viewBox="0 0 20 20" fill="currentColor" className={className} aria-hidden="true">
<path
fillRule="evenodd"
d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
clipRule="evenodd"
/>
</svg>
);
}
Loading