Rbtz.CredoChecks.Readability.ClassAttrFormatting (rbtz_credo_checks v0.4.0)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of normal and works with any version of Elixir.

Explanation

Enforces two layout rules for HEEx class attributes:

  1. Interpolated attrs with multiple values must use list syntax. Comma-separated content inside class={} without surrounding brackets either fails to compile or is silently parsed as a tuple/keyword list. Wrap them in [...]. The most common shape this catches in practice is an unparenthesized if whose keyword-list commas leak to the top level of the attribute expression.

  2. No class-attribute line may exceed the max line length. Whether the attribute is on one line or broken across many, every source line spanned by a class={...} or class="..." attribute must stay within :max_line_length characters as displayed by the editor (default 98, matching the Elixir formatter convention). Long lines — whether a flat single-line attribute or one long string literal buried inside a multi-line list — should be split into shorter logical groups.

The check inspects every ~H sigil and every .heex template referenced via embed_templates. Both rules can be violated by the same attribute; you'll get one issue per attribute. Line length is measured against the full source line (String.length/1 of the line text, i.e. the column position the editor shows).

Configure via :max_line_length (default 98).

Bad — comma-separated without brackets

<a class={if @cond, do: "x", else: "y"}>...</a>

Bad — single-line class attr exceeds the line limit

<a class={["px-2 text-white", "py-5 bg-blue-600", "rounded-md border border-transparent"]}>x</a>
<a class="px-2 text-white py-5 bg-blue-600 rounded-md border border-transparent hover:underline">x</a>

Bad — a single string inside a multi-line class attr exceeds the limit

<a class={[
  "px-2 py-1 text-white bg-blue-600 rounded-md border border-transparent hover:underline focus:ring-2",
  @extra
]}>x</a>

Good

<a class={if(@cond, do: "x", else: "y")}>...</a>

<a class={[
  "px-2 text-white",
  "py-5 bg-blue-600",
  "rounded-md border border-transparent",
  "hover:underline"
]}>x</a>

Check-Specific Parameters

There are no specific parameters for this check.

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.