aptinio

aptinio

I just published canonical_tailwind, a formatter plugin that canonicalizes Tailwind CSS utility classes in HEEx templates.

- mr-4 custom-btn flex ml-[1rem] flex
+ custom-btn mx-4 flex

It delegates to the tailwindcss CLI’s new canonicalize subcommand — the same engine that powers the Prettier plugin. So you get sorting, normalization, and duplicate collapsing powered directly by the Tailwind CSS engine.

It hooks into mix format via Phoenix LiveView 1.1’s attribute_formatters API and works with LSP format-on-save (tested with Expert).

Setup is two lines — one dep, one formatter config:

# mix.exs
{:canonical_tailwind, "~> 0.1.0", only: [:dev, :test], runtime: false}
# .formatter.exs
[
  plugins: [Phoenix.LiveView.HTMLFormatter],
  attribute_formatters: %{class: CanonicalTailwind},
]

If you’re already using the :tailwind hex package, it detects your binary and profile automatically. Make sure your tailwind version in config/config.exs is at least 4.2.2 and run mix tailwind.install after changing it.

Requires Elixir ~> 1.18, Phoenix LiveView ~> 1.1, and tailwindcss CLI >= 4.2.2 (the first version with canonicalize). The canonicalize --stream flag that makes this possible was merged in tailwindcss#19796.

Hex: canonical_tailwind | Hex
Docs: canonical_tailwind v0.3.0 — Documentation

https://github.com/aptinio/canonical_tailwind

Showing Posts 1 to 10

webuhu

webuhu

Very cool. Thanks for your contributions.
It’s the formatter I’ve been waiting for.

aptinio

aptinio OP

It was a long time coming. I first opened a PR for Phoenix LiveView asking the team to make HTMLFormatter.tokenize/1 public. José Valim came back with a better idea — attribute_formatters (phoenix_live_view#3781) — which gave formatters a proper hook into the template pipeline.

The initial implementation parsed Tailwind’s output CSS to derive the sort order. It worked, but I was never happy with it, especially with format-on-save enabled in an editor. The ideal solution was to hand the formatting off to Tailwind itself, and that became possible once the canonicalize subcommand landed. I contributed a --stream flag (tailwindcss#19796) so the CLI could stay alive as a long-running process, and after that the library was the easy part.

Hope you find it useful!

vicb335

vicb335

Damn this makes working on liveview even better, thanks so much!!

aptinio

aptinio OP

Best part about it for me is you stop thinking about class order — write whatever, hit save, done. On a team it’s even better because diffs stay clean and everyone’s output looks the same.

sevenseacat

sevenseacat

Author of Ash Framework

Very awesome!

Now we just need Tailwind to expose something to allow merging and overriding of classes…

aptinio

aptinio OP

Thanks! Interestingly, Tailwind’s canonicalize subcommand already resolves conflicts within a single class string — if you give it bg-blue-500 px-4 bg-red-500, it’ll collapse that down to bg-red-500 px-4. Last one wins.

The tricky part is that the interesting merge case is runtime — something like class={["bg-blue-500 px-4", @class]} where one side is dynamic. A formatter can’t resolve that since it doesn’t know the value of @class at format time. And doing it at runtime would mean either shipping and running the Tailwind binary in prod, or reimplementing its conflict resolution in pure Elixir — both non-trivial.

Would be a great project though!

simoncocking

simoncocking

Unsure whether this is canonical_tailwind or Tailwind’s canonicalize subcommand, but I just added canonical_tailwind to our (quite large) project and ran into a couple of issues:

  1. We had one instance where classes were wrapped in a ~s’’’ heredoc, and the parser crashed (failing to find the closing '’’).

  2. There were many instances where the formatter swapped class strings between nearby but different HTML elements.

  3. There were several instances where multi-line class strings were truncated (the formatter dropped continuation lines) - these in classes such as:

    <div class={[
      “class …”,
      “class …”,
      …
    ]}>
    

[edit]
That last one may have been in classes such as

<div class="class class class
class class class">
  • that is, where a linebreak breaks the class string.
aptinio

aptinio OP

Thanks for trying this out on a large project and sharing what you ran into!

All three are symptoms of the same bug — newlines in class strings broke the line-based protocol with the tailwindcss CLI. Multi-line strings got truncated, and subsequent attributes received stale responses (which looked like classes swapping between elements). The heredoc crash was a related issue where trailing newlines got stripped, producing invalid Elixir.

Fixed in v0.1.1. One thing to note: multi-line class strings are now collapsed into a single line, since tailwindcss canonicalize always returns a single line. If you prefer breaking long class lists across lines, you can use a list instead:

class={["flex items-center justify-between", "bg-white rounded-lg shadow-md p-4"]}

Let me know if you’re still seeing issues after upgrading.

simoncocking

simoncocking

Thanks for the quick fix - the new version is certainly much better! I’m not seeing any of the same issues with mix format, however a couple of things I notice:

  1. The formatter collapses multi-line class strings into a single, very long line. We tend to wrap very long classes over multiple lines for readability, but although mix format no longer crashes and does canonicalize, it collapses these multiple-line strings into a single line every time. This is probably a difficult one to solve - understandably the lines have to be joined in order to canonicalize, so wrapping and formatting them in the same way afterwards is tricky. We can certainly standardize on multiple strings in an array.
  2. Formatting via ElixirLS (format-on-save) is still failing on ~s''' delimited class strings with Unable to format: token missing on lib/myapp_web/live/components/thing.ex:8:2: error: missing terminator: ‘’’ (for heredoc starting at line 5), even though mix format works.
aptinio

aptinio OP

Glad it’s working better!

On the multi-line collapsing, that’s inherent to how canonicalize works. The classes have to be joined into a single string for the CLI, and there’s no way to know where the original line breaks were meaningful. Using a list of strings is probably the cleanest workaround.

On the ~s''' issue with ElixirLS, I’d need more detail to dig into that one. Could you file an issue on GitHub?

Where Next? Top

Trending in Announcing Top

wojtekmach
Hey everyone! Req is an HTTP client for Elixir that I’ve been working on for quite some time. There is already a lot of HTTP clients out...
New
handnot2
Samly can be used to enable SAML 2.0 Single Sign On in a Plug/Phoenix application. This library uses Erlang esaml to provide plug enabl...
New
woylie
Flop is an Elixir library that applies filtering, ordering and pagination parameters to your Ecto queries. offset-based pagination with...
New
MRdotB
I needed to reuse React components from my Chrome extension in my Phoenix/LiveView backend. I noticed that for Svelte/Vue, there are live...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
fuelen
Hi all! I want to present a small library which provides a mix task for generating an Entity-Relationship Diagram for Ecto schemas. You...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
AstonJ
This showed up on my feed.. anyone heard of it? Just hype? Ox Alpha is a reasoning model designed for coding, sustained ag...
New
sergio
It’s not that it’s vocabulary is too advanced. It’s something worse. I get lost trying to follow even a paragraph written by Claude. It’...
New
sorenone
Today we’re releasing Oban for Python. Not an Oban client in Python. Not a pythonx wrapper embedded in Elixir. Nope, it’s a fully operati...
New
akoutmos
@hugobarauna, Dr. Dimitrios Koutmos (my brother) and I (Alex Koutmos) have been hard at work on writing a book on how you can use Elixir ...
New
pferriby
Introductory paragraph I’ll be looking for a keen junior or someone that has a couple of years experience in the real world (so you’ve be...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews