7.2 KiB
Coding Standards
How to write code in this repo. Read the section for the layer you're touching.
Elixir
- Index lists with
Enum.at(list, i). Elixir lists don't implementAccess, solist[i]fails. - Bind the result of a block expression:
socket = if connected?(socket), do: assign(socket, :val, val). Rebinding inside the block doesn't escape it. - One module per file — nested modules invite cyclic dependencies.
- Read struct fields directly (
my_struct.field). Structs don't implementAccess; for changesets useEcto.Changeset.get_field/2. - Convert user input with
String.to_existing_atom/1or a fixed map of atoms —String.to_atom/1leaks atoms. - Predicates end in
?. Reserve theis_prefix for guards. - Name OTP primitives in their child spec:
{DynamicSupervisor, name: Chesstrainer.MyDynamicSup}, thenDynamicSupervisor.start_child(Chesstrainer.MyDynamicSup, spec). - Enumerate concurrently with
Task.async_stream(collection, fun, timeout: :infinity). - Date and time come from stdlib
Time,Date,DateTime,Calendar.date_time_parseris the only parsing dep we allow; ask before adding another. - HTTP requests use
Req(already a dep).:httpoison,:teslaand:httpcare not used.
Ecto
- Preload associations that templates touch, e.g.
message.user.email. - Every text column is
:string, including:textones:field :name, :string. validate_number/2has no:allow_nil— validations only run on a present change, so the option is redundant.- Programmatic fields like
user_idare set on the struct at insert time, never listed incast. - Generate migrations with
mix ecto.gen.migration name_using_underscoresso the timestamp and conventions are right. priv/repo/seeds.exsneedsimport Ecto.Query.
Phoenix
scopeprefixes its routes' alias:scope "/admin", ChesstrainerWeb.Adminmakeslive "/users", UserLiveresolve toChesstrainerWeb.Admin.UserLive. Adding your ownaliasduplicates the prefix.Phoenix.Viewis not part of Phoenix any more.
HEEx
-
Templates are
~Hor.html.heex. -
Begin every LiveView template with
<Layouts.app flash={@flash} ...>.Layoutsis already aliased inchesstrainer_web.ex. -
<.flash_group>lives only inlayouts.ex. -
A missing
current_scopeassign means the route sits in the wronglive_session. Move it there and passcurrent_scopethrough. -
Icons come from
core_components.ex:<.icon name="hero-x-mark" class="w-5 h-5"/>. -
Multiple conditionals use
condorcase. -
Literal
{/}inside<pre>or<code>: annotate the parent tag withphx-no-curly-interpolation. Dynamic<%= ... %>still works inside it. -
Class attributes use list syntax, with
ifwrapped in parens:<a class={[ "px-2 text-white", @some_flag && "py-5", if(@other_condition, do: "border-red-500", else: "border-blue-100") ]}>Text</a> -
Generate collections with
<%= for item <- @collection do %>. -
Comments use
<%!-- ... --%>. -
Interpolate attributes and tag bodies with
{...}.<%= %>is for block constructs in tag bodies.
LiveView
- Navigate with
<.link navigate={href}>and<.link patch={href}>; usepush_navigateandpush_patchin handlers. - Name LiveViews
SomethingLive. The:browserscope is already aliased toChesstrainerWeb, solive "/weather", WeatherLiveis enough. - Reach for a LiveView before a LiveComponent; a LiveComponent earns its place when it needs isolated state or genuine reuse.
Streams
- Assign collections through streams: append
stream(socket, :messages, [msg]), resetstream(socket, :messages, msgs, reset: true), prependat: -1, removestream_delete(socket, :messages, msg). - The parent element carries
phx-update="stream"and a DOM id; each child is:for={{id, msg} <- @streams.messages} id={id}. - Streams aren't enumerable. To filter, refetch the data and re-stream it with
reset: true. - Streams don't count or render empty states. Track the count in a separate assign, and put the empty state in a
hidden only:blocksibling of the:for. - When an assign changes content inside streamed items, re-stream the item with
stream_insert/3so the item re-renders.
Hooks
-
A
phx-hookelement needs a unique DOM id, plusphx-update="ignore"when the hook owns its DOM. -
Client-side JS is a colocated hook inside the template:
<script :type={Phoenix.LiveView.ColocatedHook} name=".PhoneNumber"> export default { mounted() { ... } } </script>The leading
.on the name is required. Hooks shared across pages live inassets/js/hooks/and are passed toLiveSocket. -
push_event/3returns the socket — rebind it or return it from the handler. -
In the hook:
this.handleEvent("name", data => ...)receives,this.pushEvent("name", payload, reply => ...)sends. The server replies with{:reply, payload, socket}.
Forms
-
Build the form in the LiveView with
to_form/2, pass it to<.form for={@form} id="...">, and read fields as@form[:field]through<.input>:assign(socket, form: to_form(changeset)) <.form for={@form} id="todo-form" phx-change="validate" phx-submit="save"> <.input field={@form[:field]} type="text" /> </.form> -
to_form/1on a plain map expects string keys. Nest params withto_form(params, as: :user). -
From a changeset:
Ecto.Changeset.change(user) |> to_form(). Submitted params arrive as%{"user" => ...}. -
Every form gets a unique DOM id — the tests select on it.
-
<.input>with custom classes inherits none of the defaults, so style it fully.
Assets
assets/css/app.cssis authoritative for the Tailwind v4 setup:@import "tailwindcss" source(none), the@sourcelines, the chessground stylesheets andphoenix-colocated/chesstrainer/colocated.css. Keep that import block current.- Custom CSS uses plain declarations.
@applyis off-limits. - Components are hand-written Tailwind. daisyUI is not used.
- Only the
app.jsandapp.cssbundles ship. Vendor dependencies are imported into them, not linked from layouts.
Testing
-
Start processes with
start_supervised!/1. -
Wait for a process with
Process.monitor/1andassert_receive {:DOWN, ^ref, :process, ^pid, :normal}instead ofProcess.sleep/1. -
Synchronise before the next call with
_ = :sys.get_state(pid). -
LiveView tests use
Phoenix.LiveViewTestandLazyHTML; drive forms withrender_submit/2andrender_change/2. -
Assert on elements with the ids from the template:
assert has_element?(view, "#my-form"),element/2. Text content changes; ids don't. -
Debug a stubborn selector:
html = render(view) document = LazyHTML.from_fragment(html) matches = LazyHTML.filter(document, "your-complex-selector") IO.inspect(matches, label: "Matches")
Precommit
mix precommit runs compile --warnings-as-errors, deps.unlock --unused, format and test.
Type checking (Dialyzer)
dialyxir is available in dev/test; run:
mix dialyzer
It is intentionally not part of mix precommit: the first run builds a PLT
(several minutes), though subsequent runs are fast. The PLT lives under
_build/ (gitignored).
Treat warnings as bugs — add @specs or fix them. Only suppress with
@dialyzer or .dialyzer_ignore.exs when accompanied by a comment explaining
why.