diff --git a/AGENTS.md b/AGENTS.md index 9df83d2..cb4deeb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,8 +30,8 @@ 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.}`), never a raw `` 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 }) => ( )`) are fine @@ -39,7 +39,7 @@ These are the rules that must not be forgotten or looked up — they're the ones - **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 (``, `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/_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/_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 @@ -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 `**, never against :4000. It starts its own server on a free port with its own database (`elixir_react_starter_e2e_`), 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 @@ -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:` 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`) diff --git a/README.md b/README.md index 122eb83..14795c8 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/assets/biome.jsonc b/assets/biome.jsonc index 85bea92..38dbb41 100644 --- a/assets/biome.jsonc +++ b/assets/biome.jsonc @@ -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." } } }, @@ -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": { diff --git a/assets/build/watch-generated.cjs b/assets/build/watch-generated.cjs new file mode 100644 index 0000000..705bb98 --- /dev/null +++ b/assets/build/watch-generated.cjs @@ -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(); diff --git a/assets/build/watch-routes.cjs b/assets/build/watch-routes.cjs deleted file mode 100644 index 9b1a2c9..0000000 --- a/assets/build/watch-routes.cjs +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; -// Watches the Phoenix router for changes and regenerates the typed frontend -// route table (assets/js/routes.ts) via `mix routes.gen`. Used as a Phoenix -// dev watcher so routes.ts can't go stale while the dev server is running. -// -// Router edits are rare, so shelling out to `mix` (which boots a second BEAM) -// on change is an acceptable cost — and it reuses the exact same generator -// that assets.build and precommit use, so there's only one source of truth. - -const path = require('node:path'); -const { execFileSync } = require('node:child_process'); - -const ROOT = path.join(__dirname, '..', '..'); -const ROUTER = path.join(ROOT, 'lib', 'elixir_react_starter_web', 'router.ex'); - -function regenerate() { - try { - execFileSync('mix', ['routes.gen'], { cwd: ROOT, stdio: 'inherit' }); - } catch { - // errors already printed by the child process - } -} - -// Initial generation so a freshly-started server is always in sync. -regenerate(); - -// fs.watch on the single router file is enough — every route lives there. -require('node:fs').watch(ROUTER, () => regenerate()); - -// Keep process alive -process.stdin.resume(); diff --git a/assets/build/watch-ssr-pages.cjs b/assets/build/watch-ssr-pages.cjs deleted file mode 100644 index 3d46d3f..0000000 --- a/assets/build/watch-ssr-pages.cjs +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; -// Watches assets/js/pages/ for added/removed .tsx files and regenerates the -// SSR pages registry. Used as a Phoenix dev watcher. - -const fs = require('node:fs'); -const path = require('node:path'); -const { execFileSync } = require('node:child_process'); - -const PAGES_DIR = path.join(__dirname, '..', 'js', 'pages'); -const GENERATE = path.join(__dirname, 'generate-ssr-pages.cjs'); - -function regenerate() { - try { - execFileSync(process.execPath, [GENERATE], { stdio: 'inherit' }); - } catch { - // errors already printed by the child process - } -} - -// Initial generation -regenerate(); - -// Watch for changes (recursive) -fs.watch(PAGES_DIR, { recursive: true }, (_event, filename) => { - if (filename?.endsWith('.tsx')) { - regenerate(); - } -}); - -// Keep process alive -process.stdin.resume(); diff --git a/assets/js/app.tsx b/assets/js/app.tsx index cd51411..9e348ea 100644 --- a/assets/js/app.tsx +++ b/assets/js/app.tsx @@ -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'; diff --git a/assets/js/architecture.test.ts b/assets/js/architecture.test.ts new file mode 100644 index 0000000..a361057 --- /dev/null +++ b/assets/js/architecture.test.ts @@ -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(/(?^|\s)\/\/.*$/gmu, '$'); +} + +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.() from routes.ts'); +}); diff --git a/assets/js/components/LocaleSelector.tsx b/assets/js/components/LocaleSelector.tsx index 2a9f73f..baa7306 100644 --- a/assets/js/components/LocaleSelector.tsx +++ b/assets/js/components/LocaleSelector.tsx @@ -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'; @@ -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]; @@ -32,11 +34,11 @@ export default function LocaleSelector({ className = '' }: LocaleSelectorProps) return ( - + {locales.map(({ code, label, flag: Flag }) => ( @@ -81,15 +83,3 @@ function FlagES({ className }: { className?: string }) { ); } - -function ChevronDown({ className }: { className?: string }) { - return ( - - ); -} diff --git a/assets/js/components/TextField.tsx b/assets/js/components/TextField.tsx new file mode 100644 index 0000000..5ec0cb1 --- /dev/null +++ b/assets/js/components/TextField.tsx @@ -0,0 +1,57 @@ +import { type InputHTMLAttributes, useId } from 'react'; + +interface TextFieldProps extends Omit, 'id' | 'value' | 'onChange'> { + label: string; + value: string; + onChange: (value: string) => void; + /** Server validation message for this field (`useForm().errors.`). */ + error?: string; + /** Keep the label for screen readers only, when the surrounding UI already names the field. */ + hideLabel?: boolean; +} + +const inputClass = + 'w-full rounded border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900 px-3 py-2 text-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-primary aria-invalid:border-red-600'; + +/** + * The one form text input: label, input and error message, wired together for + * assistive tech (`htmlFor`, `aria-invalid`, `aria-describedby`). Pages use this + * instead of a raw ``. + */ +export default function TextField({ + label, + value, + onChange, + error, + hideLabel = false, + className = '', + 'aria-describedby': describedBy, + ...rest +}: TextFieldProps) { + const id = useId(); + const errorId = `${id}-error`; + // Keep a caller's own description (e.g. hint text) alongside the error. + const describedByIds = [describedBy, error ? errorId : undefined].filter(Boolean).join(' ') || undefined; + + return ( +
+ + onChange(e.target.value)} + className={inputClass} + aria-invalid={error ? true : undefined} + aria-describedby={describedByIds} + {...rest} + /> + {error ? ( +

+ {error} +

+ ) : null} +
+ ); +} diff --git a/assets/js/components/ui.ts b/assets/js/components/ui.ts deleted file mode 100644 index e134112..0000000 --- a/assets/js/components/ui.ts +++ /dev/null @@ -1,3 +0,0 @@ -// Shared Tailwind classes for native form inputs. -export const inputClass = - 'w-full rounded border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900 px-3 py-2 text-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-primary'; diff --git a/assets/js/i18n/locales/en.ts b/assets/js/i18n/locales/en.ts index abc4f0a..e1766c8 100644 --- a/assets/js/i18n/locales/en.ts +++ b/assets/js/i18n/locales/en.ts @@ -15,6 +15,7 @@ export default { themeLight: 'Light', themeDark: 'Dark', themeSystem: 'System', + changeLanguage: 'Change language', }, error: { title: 'Something went wrong', diff --git a/assets/js/i18n/locales/es.ts b/assets/js/i18n/locales/es.ts index 52ec041..7692459 100644 --- a/assets/js/i18n/locales/es.ts +++ b/assets/js/i18n/locales/es.ts @@ -15,6 +15,7 @@ export default { themeLight: 'Claro', themeDark: 'Oscuro', themeSystem: 'Sistema', + changeLanguage: 'Cambiar idioma', }, error: { title: 'Algo salió mal', diff --git a/assets/js/components/syncLocale.ts b/assets/js/i18n/syncLocale.ts similarity index 100% rename from assets/js/components/syncLocale.ts rename to assets/js/i18n/syncLocale.ts diff --git a/assets/js/pages/client/Settings.tsx b/assets/js/pages/client/Settings.tsx index d0843aa..cf0fc54 100644 --- a/assets/js/pages/client/Settings.tsx +++ b/assets/js/pages/client/Settings.tsx @@ -1,5 +1,5 @@ import { useForm, usePage } from '@inertiajs/react'; -import { useId, useState } from 'react'; +import { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { AlertDialog, @@ -11,7 +11,7 @@ import { AlertDialogTrigger, } from '../../components/AlertDialog'; import Button from '../../components/Button'; -import { inputClass } from '../../components/ui'; +import TextField from '../../components/TextField'; import AppLayout from '../../layouts/AppLayout'; import { routes } from '../../routes'; @@ -32,7 +32,6 @@ export default function Settings() { function ChangeEmailSection() { const { t } = useTranslation(); - const id = useId(); const currentEmail = usePage().props.current_user?.email ?? ''; const { data, setData, put, processing, errors, reset } = useForm({ current_password: '', @@ -54,37 +53,25 @@ function ChangeEmailSection() { }} className="space-y-4" > -
- - setData('email', e.target.value)} - className={inputClass} - required - /> - {errors.email ?

{errors.email}

: null} -
- -
- - setData('current_password', e.target.value)} - className={inputClass} - required - /> - {errors.current_password ?

{errors.current_password}

: null} -
+ setData('email', value)} + required + error={errors.email} + /> + + setData('current_password', value)} + required + error={errors.current_password} + />