# petal_components - rules for AI coding assistants

petal_components is a shadcn-style component library for Phoenix LiveView. Components live in modules under `PetalComponents.*` and are called as plain HEEx tags (`<.button>`, `<.modal>`, `<.table>`) once you `use PetalComponents`. CSS classes use a `pc-` prefix for styling overrides (`pc-button`, `pc-button--primary`). Use these rules to write idiomatic Phoenix UI instead of inventing raw Tailwind markup.

Drop this file into your AI coding tool's rules system (Cursor `.cursorrules`, Claude Code `CLAUDE.md`, Codex `AGENTS.md`, Continue rules, etc.) when working in a Phoenix project that has `petal_components` installed.

## Installing petal_components

When the user says "install petal_components" (or you're starting in a Phoenix project that doesn't have it yet), follow these steps. They are idempotent - safe to re-run if any step is partially done.

### 1. Add the dependency

Open `mix.exs`. In the `deps/0` function, add this line if it's not already there:

```elixir
{:petal_components, "~> 4.18"}
```

If the user wants the chat components (`PetalComponents.Chat`: `<Chat.conversation>`, `<Chat.markdown>`, `<Chat.rich_text>` and the rest), also add the optional `{:mdex, "~> 0.12"}`. If the user wants `<.qr_code>`, also add the optional `{:eqrcode, "~> 0.2"}`; without it, rendering a QR code raises an error that says to add it. The other components need no extra deps. The Chat family is not pulled in by `use PetalComponents`: add `alias PetalComponents.Chat` and call it namespaced.

### 2. Fetch dependencies

```sh
mix deps.get
```

Releases up to and including 4.18.0 declared `websock_adapter ~> 0.5.7`, which a new Phoenix 1.8 app's `mix.lock` (websock_adapter 0.7.x) does not satisfy, so resolution fails with a message naming `websock_adapter`. Later releases do not declare it. If you see that failure, run `mix deps.unlock websock_adapter && mix deps.get`.

### 3. Configure Tailwind CSS

Open `assets/css/app.css` and find the existing `@import "tailwindcss"` line (Phoenix 1.8 writes it as `@import "tailwindcss" source(none);`). Leave that line exactly as it is and do not add a second `@import "tailwindcss"`. Directly below it, add these four lines:

```css
@source "../../deps/petal_components/**/*.*ex";
@source not "../../deps/petal_components/lib/petal_components/showcase";
@import "../../deps/petal_components/assets/default.css";
@plugin "@tailwindcss/forms";
```

When you are done, `app.css` contains exactly one `@import "tailwindcss"` line.

The `@source` line tells Tailwind to scan petal_components source for class usage. The `@source not` line skips the `showcase/` example modules - those power petal.build's own docs, not your app, so scanning them would only add unused utility classes to your CSS. (`@source not` needs Tailwind v4.1+. On v4.0 it's harmless to drop the line; you just get a little extra CSS.) The `@import` line brings in the default component styles (the `pc-*` CSS prefix).

The `@plugin` line loads `@tailwindcss/forms`. The form components are styled on top of it: the plugin sets the border width and padding on text inputs, selects and textareas, and resets the native look of checkboxes and selects. Without it, Tailwind's preflight leaves inputs with no border and no padding. Skip the line if the app already loads the plugin. The `tailwind` Hex package that Phoenix uses runs the standalone Tailwind CLI, which already includes the plugin, so there is nothing to install. If the app builds Tailwind through Node instead, run `npm install -D @tailwindcss/forms` in `assets/`.

`<.prose>` renders Tailwind's `prose` classes, which come from the `@tailwindcss/typography` plugin. Without the plugin the content inside `<.prose>` has no typography styles at all. If the app uses `<.prose>`, add `@plugin "@tailwindcss/typography";` below the forms line, unless the app already loads it. The standalone Tailwind CLI includes this plugin too, so there is nothing to install; with a Node build, run `npm install -D @tailwindcss/typography` in `assets/`.

If there is no `@import "tailwindcss"` line, the project is on Tailwind v3 and petal_components 4.x will not work. Tell the user to upgrade to Tailwind v4, or pin to `petal_components ~> 1.0` for Tailwind v3 support.

### 4. Import the components in your web module

Find `lib/<your_app>_web.ex`. In umbrella apps it lives at `apps/<your_app>_web/lib/<your_app>_web.ex`. The file defines `def html`, `def live_view`, `def live_component` and a private `defp html_helpers`. All three of the public ones `unquote(html_helpers())`, but `def live_view` does not go through `def html`, so an import placed in `def html` never reaches a LiveView. Put it in `html_helpers`.

Phoenix 1.8's generated `core_components.ex` defines `button/1`, `icon/1`, `input/1` and `table/1`, the same names petal_components exports. Importing both makes every call to those four ambiguous, and the app stops compiling (`function icon/1 imported from both <YourApp>Web.CoreComponents and PetalComponents.Icon, call is ambiguous`, first in the generated `Layouts`). So exclude those four from the CoreComponents import. Inside `defp html_helpers`, change the generated line

```elixir
import MyAppWeb.CoreComponents
```

to these two lines:

```elixir
use PetalComponents
import MyAppWeb.CoreComponents, except: [button: 1, icon: 1, input: 1, table: 1]
```

(with your app's module name in place of `MyAppWeb`). The rest of CoreComponents (`flash/1`, `header/1`, `list/1` and the others) stays imported. If the compiler reports another `call is ambiguous` name (apps generated by older Phoenix versions also define `modal/1`, for example), add it to the `except:` list the same way. If `use PetalComponents` is already in `html_helpers`, skip this step; if it is in `def html`, move it.

`use PetalComponents` imports the components so you can call them as `<.button>`, `<.modal>`, etc. without explicit aliases. The one component family it does not import is Chat (`PetalComponents.Chat`, see step 1), which you alias and call as `<Chat.markdown>` and so on. The other modules it leaves out are not meant to be called from your templates: `PetalComponents.DataTable.FilterEditor`, which `<.data_table>` and `<.filters>` render for you; the old `HeroiconsV1` icon sets, which it aliases as `HeroiconsV1` (use `<.icon name="hero-...">` instead); and the `Showcase` and `Svg` helpers the library uses for its own docs and icons.

After this, `<.button>`, `<.icon>`, `<.input>` and `<.table>` everywhere in the app are the petal_components versions, which take different attributes from the CoreComponents ones. A fresh `phx.new` app compiles unchanged (its layouts only call `<.icon name="hero-...">`, which petal_components renders the same way). Pages written by `mix phx.gen.live` or `mix phx.gen.auth`, before or after the install, call the CoreComponents versions and need their call sites updated:

- `<.input field={@form[:email]} type="email" label="Email" />` becomes `<.field field={@form[:email]} type="email" label="Email" />`. petal_components' `<.input>` is the bare control and renders no label and no errors, so keeping `<.input label=...>` silently drops both.
- `<.button variant="primary">` becomes `<.button>` (solid primary is the default). A `<.button>` with no `variant` was the CoreComponents soft style (Cancel buttons, for example); make it `<.button variant="soft">` so it does not turn solid. `<.button navigate={~p"/path"}>` becomes `<.button link_type="live_redirect" to={~p"/path"}>`.
- Remove the daisyUI `btn`, `btn-primary`, `btn-soft` and other `btn-*` classes from a button's `class` (`phx.gen.auth` writes `class="btn btn-primary w-full"`). petal_components adds `class` to its own classes, so they would stack two button styles on one element. Keep layout classes such as `w-full`.
- `<.table>` has no `:action` slot. Move the row actions into a last `<:col :let={row} label="">`. `rows={@streams.items}` works as before. With `row_click` set, petal_components puts the row click on every cell, so the actions cell gets it too; drop `row_click` if the row should not open the record.
- Generated tests that match exact input HTML (for example `phx.gen.auth`'s login test asserting `~s(<input type="email" name="user[email]" ...)`) fail, because petal_components renders the attributes in a different order with its own classes. Rewrite them with `has_element?/2` and a selector.

`mix compile --warnings-as-errors` flags the `variant="primary"`, `navigate` and `:action` call sites. It does not flag `<.input label=...>` or the `btn-*` classes. A leftover `<.input label=...>` compiles and renders with no label and no errors; the generated LiveView tests catch it (their `can't be blank` assertions fail), so run `mix test` after the edits, and search the templates for `<.input` and `btn` as well. To keep one generated page exactly as generated instead, call the core component by its module: `<MyAppWeb.CoreComponents.input field={@form[:email]} label="Email" />`.

### 4b. Route form errors through your app's translator

In `config/config.exs`, add:

```elixir
config :petal_components, :error_translator_function, {MyAppWeb.CoreComponents, :translate_error}
```

(with your app's module name in place of `MyAppWeb`). Phoenix generates `translate_error/1` in `core_components.ex`, and it runs errors through Gettext. Without this line petal_components falls back to plain `%{key}` substitution, which cannot handle the list options some Ecto validations add: `unsafe_validate_unique` (used by `phx.gen.auth`) adds `fields: [:email]`, so "has already been taken" renders as "invalid value" and a warning is logged. If the app already sets `:error_translator_function`, skip this step.

### 5. Register the JS hooks

petal_components v4 ships a bundled JS hook set that many components need: toasts, dropdowns and popovers, alert dialogs, the command palette, the combobox, the data table, the date picker and calendar, sliders, charts, the chat family, the enhanced inputs and more. Without the hooks those components still render, but their interactive behaviour is missing and the browser console reports an unknown hook. You never register hooks individually - spread the whole set once. Open `assets/js/app.js`, import the hooks, and merge them into your `LiveSocket`:

```js
import PetalComponents from "../../deps/petal_components/assets/js/petal_components"

const liveSocket = new LiveSocket("/live", Socket, {
  params: { _csrf_token: csrfToken },
  hooks: { ...PetalComponents }, // merge with existing hooks: { ...MyHooks, ...PetalComponents }
})
```

Phoenix 1.8 already passes `hooks: {...colocatedHooks}`; make it `hooks: {...colocatedHooks, ...PetalComponents}`.

If the project has no `assets/js/app.js` (an API-only or minimal app), skip this step: only the interactive components need the hooks.

### 5b. Charts (only if the app uses `<.chart>`)

The `<.chart>` component drives Apache ECharts but does not bundle it — the engine is bring-your-own, exactly like Alpine. Add it ONLY when the app actually renders a `<.chart>`; skip otherwise. Either a script tag in the root layout:

```html
<script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
```

or `npm i echarts` plus `import * as echarts from "echarts"; window.echarts = echarts;` in `app.js`. The `PetalChart` hook picks it up from `window.echarts` and warns in the console if it's missing (the chart area renders empty). `<.sparkline>` is pure server-rendered SVG and needs nothing.

### 6. Update the project's agent instructions

`mix phx.new` writes an `AGENTS.md` whose Phoenix guidelines tell an agent to always use the `<.icon>` and `<.input>` components from `core_components.ex`. After step 4 those two lines are wrong for this app. In `AGENTS.md`, replace the line that starts ``- Out of the box, `core_components.ex` imports an `<.icon`` with:

```text
- `<.icon>` comes from petal_components (`use PetalComponents` in `html_helpers`). Use `<.icon name="hero-x-mark" class="w-5 h-5" />` for hero icons, **never** `Heroicons` modules or similar
```

and replace the line that starts ``- **Always** use the imported `<.input>` component`` with:

```text
- Form fields use petal_components `<.field field={@form[:name]} label="..." />` (label, input, errors and help text). `<.input>` is the petal_components bare input and renders no label
```

Delete the line after them that starts ``- If you override the default input classes`` (and its continuation line): petal_components adds your `class` to its own classes rather than replacing them. Further down, in the form section, change ``and the `<.input>` component in the template`` to ``and the `<.field>` component in the template``, and in the form examples change every `<.input field=` to `<.field field=`. If the project keeps the same guidelines in `CLAUDE.md` or another rules file, make the same change there. If the project has no `AGENTS.md` and no such file (apps made with `mix phx.new --no-agents-md`, or by Phoenix before 1.8), skip this step.

### 7. Verify

```sh
mix compile --warnings-as-errors
```

It must finish with no warnings. Warnings printed while compiling `petal_components` itself about `MDEx` or `EQRCode` are about optional dependencies and do not fail the build. Then check that a LiveView renders the library's markup, not the CoreComponents markup. A fresh `phx.new` app has no LiveView yet, so if the app has none that renders a `<.button>`, add a throwaway one:

```elixir
# lib/my_app_web/live/install_check_live.ex
defmodule MyAppWeb.InstallCheckLive do
  use MyAppWeb, :live_view

  def render(assigns), do: ~H"<.button>Hello</.button>"
end
```

with `live "/install-check", InstallCheckLive` in the router's `"/"` browser scope, and this test:

```elixir
# test/my_app_web/live/install_check_live_test.exs
defmodule MyAppWeb.InstallCheckLiveTest do
  use MyAppWeb.ConnCase, async: true
  import Phoenix.LiveViewTest

  test "renders petal_components", %{conn: conn} do
    {:ok, view, _html} = live(conn, ~p"/install-check")
    assert has_element?(view, "button.pc-button")
  end
end
```

Run `mix test`, then delete the three throwaway pieces. Finally run `mix assets.build` and confirm `priv/static/assets/css/app.css` contains `.pc-button`.

### 8. Brand colours (optional)

Components work out of the box: petal_components ships default colour ramps (blue `primary`, pink `secondary`, semantic hues, zinc `gray`). They are soft defaults (`@theme default`), so a plain `@theme` block in the project's `app.css` wins no matter where it sits relative to the import:

```css
@theme inline {
  --color-primary-50: var(--color-violet-50);
  --color-primary-100: var(--color-violet-100);
  /* ...one line per stop, 50-950, for any ramp you want to change... */
  --color-primary-950: var(--color-violet-950);
}
```

The roles: `primary` is the base action colour and tints every variant of every component (solid fills, outline borders, ghost text); `secondary` is a second brand accent with the same rule; `info`/`success`/`warning`/`danger` carry meaning and should stay recognisable; `gray` is the neutral chrome. Map a role to any Tailwind hue by referencing that hue's variables, or use literal values.

One deliberate choice to know about: the `gray` role ships Tailwind's **zinc** values under the gray name, so one coherent neutral runs through every component. Because `--color-gray-*` is a shared namespace, this also sets what the app's own `text-gray-*` / `bg-gray-*` utilities render as. To use a different neutral, remap it like any other role (`--color-gray-50: var(--color-slate-50);` and so on per stop - slate, stone, neutral and zinc all remain available as variables). The one palette a `var()` cannot reach is Tailwind's original gray itself (its values only ever lived under the name petal_components now occupies), so restoring it is a one-line import after the default styles:

```css
@import "../../deps/petal_components/assets/default.css";
@import "../../deps/petal_components/assets/tailwind-gray.css";
```

### 9. Type (optional)

Components inherit the host app's font stack - that is the default and it stays. Three opt-in tokens exist for when a design wants distinct faces; the package only READS them (never defines them), so an app that sets nothing changes nothing:

- `--pc-font-heading` - the heading components (`<.h1>`..`<.h5>`) and prose headings. Falls back through `--pc-font-body`, then `inherit`, so setting body alone moves headings too.
- `--pc-font-body` - the reading surfaces: the typography components, `<.prose>`, chat. Falls back to `inherit`. Kbd chips follow this token as well - they are deliberately never mono.
- `--pc-font-mono` - inline code, tool output, and every other pc mono surface. Falls back through Tailwind's `--font-mono`.

For a whole-app face, do not reach for these: set Tailwind's own theme font and preflight reskins everything, pc components included:

```css
@theme {
  --font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
}
```

The pc tokens cover what `--font-sans` cannot express: a heading face distinct from body (`:root { --pc-font-heading: "Fraunces", ui-serif, Georgia, serif; }`), or scoping faces to a subtree (set the token on any wrapper - custom properties re-resolve per subtree, useful for multi-brand areas). Only `<.h1>`..`<.h5>` and prose headings bind the heading token; raw `<h1>`-`<h6>` markup that should follow it needs one extra line: `h1, h2, h3, h4, h5, h6 { font-family: var(--pc-font-heading, inherit); }`.

Self-hosting a face in Phoenix: fetch the variable woff2 into `priv/static/fonts/` (already served by the generated `static_paths`), add an `@font-face` with `font-display: swap` and `format("woff2-variations")` to `app.css`, and `<link rel="preload">` the body face in the root layout with `crossorigin="anonymous"`. The playground's Get Code button emits this whole story - install lines, theme block, font files, preload - for any look dialed in at https://playground.petal.build.

### Installation rules of thumb for AI agents

- Read each file before editing. Do not blind-patch.
- If the project already uses `petal_components`, skip the steps that are already done. Report what was already in place.
- After installing, suggest calling `list_components` to see what's available.

## Hard rules

1. **Prefer a petal_components tag over raw HTML.** If you would reach for a `<button>`, `<table>`, `<input>`, `<div role="dialog">`, `<select>`, or any other common UI primitive, check for a petal_components equivalent first (`<.button>`, `<.table>`, `<.text_input>`, `<.modal>`, `<.select>`).
2. **Do not invent Tailwind soup for things petal_components already does.** No hand-rolled modal divs, no manual dropdown JS, no DIY form labels. There is almost certainly an existing component for it.
3. **Look up the schema before guessing attrs.** Do not assume attr names from memory. Call `list_components` and `get_component` (see below) to get the real attr/slot signature before writing HEEx.
4. **Call components as plain HEEx tags after `use PetalComponents`.** `<.button>`, `<.modal>`, `<.table>`, `<.card>`, etc. If you have not imported, qualify with the module: `<PetalComponents.Button.button />`. Note: the `pc-*` prefix you see in source is the CSS class prefix for styling, not part of the function name.
5. **Components work in both live and dead views.** Interactivity is Phoenix.LiveView.JS only (no Alpine.js as of v4). Many components (toasts, command palette, colour scheme, carousel, charts, chat, combobox, data table, enhanced inputs and more) use bundled JS hooks — register the whole set once in your LiveSocket: `import PetalComponents from "../../deps/petal_components/assets/js/petal_components"` then `hooks: { ...PetalComponents }`.
6. **Form inputs come in two layers, pick deliberately.** Use `<.field type="..." />` when you want label + input + error + help text bundled (the common case in form contexts). Use the standalone primitives (`<.text_input>`, `<.select>`, `<.checkbox>`, etc.) when composing your own field layout.

## Design

These rules apply to every line of custom markup and CSS you write next to the components (anything that is not a petal_components tag). They are the floor; the full doctrine is in the design guide named at the end of this section.

- Gray is the neutral dial, not a palette. Write `bg-gray-100`, `border-gray-200`, `text-gray-700`: the app remaps the `gray` ramp. Never literal `slate-*`, `zinc-*`, `stone-*` or `neutral-*` in chrome.
- Every light-mode colour class carries its `dark:` pair in the same class string. No unpaired colours.
- Text sits on three tiers: headings `text-gray-900 dark:text-white`, body `text-gray-700 dark:text-gray-100`, muted `text-gray-500 dark:text-gray-400`.
- Dark translucent chrome is alpha of gray-400, never white alpha and never opaque gray-800 on ghost surfaces: `dark:bg-gray-400/8` resting surface, `dark:hover:bg-gray-400/17` hover wash, `dark:border-gray-400/17` panel hairline, `dark:border-gray-400/25` input border and active wash.
- Opaque panels: `bg-white dark:bg-gray-900`, hairline `border-gray-200 dark:border-gray-400/17`. `shadow-xs` resting, `shadow-lg` or `shadow-xl` for floating panels, no `shadow-md`.
- Radius comes from one knob: `var(--pc-radius, 0.625rem)` on custom controls, clamped to `min(var(--pc-radius, 0.625rem), 1rem)` on anything that can grow past one line. Never hardcode `rounded-lg` or `rounded-xl` next to the components.
- Focus is the house ring: `focus:outline-hidden focus-visible:ring-2 focus-visible:ring-primary-500/50`, plus `focus-visible:border-primary-500` on fields. Never `outline-none` without a visible replacement.
- Solid fills walk the ramp: `bg-primary-600 hover:bg-primary-700 active:bg-primary-800`. Never `hover:opacity-90` or `hover:brightness-*` on solids.
- Colour is an accent, not paint: a neutral surface, with the semantic hue arriving as an icon and a hairline rather than a tinted background flood.
- Disabled is `disabled:opacity-50 disabled:cursor-not-allowed`. Transitions are `transition-colors duration-200 ease-out`.
- Heroicon names must be source-literal: `name="hero-check-micro"` works, an interpolated name is purged by the Tailwind source scan.

Before styling custom markup or theming the app, read `deps/petal_components/guides/design.md`. To review a diff, walk its section 11, "Reviewing a diff by hand".

## Discovering components

### Recommended: the MCP server

Install once:

```sh
claude mcp add petal --transport http https://mcp.petal.build/mcp
```

Then call:

- `list_components` returns every component with a one-line summary
- `get_component <name>` returns the full schema (attrs, slots, defaults, allowed values) plus a usage example

Equivalent installs exist for Cursor, Windsurf, Continue, Codex, and Cline. See https://petal.build/petal-components for setup snippets.

### Fallback: static reference

If the MCP is unavailable, the source of truth is https://hexdocs.pm/petal_components. Each `lib/petal_components/*.ex` module documents its component with `attr` and `slot` declarations you can read directly.

## Naming conventions

- **HEEx tags**: plain component name with a leading dot, e.g. `<.button>`, `<.modal>`, `<.breadcrumbs>`. No `pc_` prefix on the function name.
- **Modules**: `PetalComponents.Button`, `PetalComponents.Modal`, `PetalComponents.Breadcrumbs`. Importing via `use PetalComponents` is the common path.
- **Form primitives**: `<.text_input>`, `<.email_input>`, `<.select>`, `<.checkbox>`, `<.switch>`, `<.textarea>`, etc. (all defined in `PetalComponents.Form`).
- **Field wrapper**: `<.field type="text" | "email" | "select" | "checkbox" | "switch" | "radio-group" | ...>`
- **CSS classes**: use the `pc-` prefix for styling overrides (e.g. `pc-button`, `pc-button--primary`, `pc-modal`). This is the only place `pc-` appears.

## Common patterns

### Form in card

```heex
<.card>
  <.card_content>
    <.form for={@form} phx-submit="save">
      <.field field={@form[:name]} label="Name" />
      <.field field={@form[:email]} type="email" label="Email" />
      <.button type="submit">Save</.button>
    </.form>
  </.card_content>
</.card>
```

### Modal with form

```heex
<.modal title="Edit user" max_width="md">
  <.form for={@form} phx-submit="save">
    <.field field={@form[:name]} label="Name" />
    <.button type="submit">Save</.button>
  </.form>
</.modal>
```

### Table with row actions

`rows` is required in practice: without it the table renders headers and an empty body, with no warning.

```heex
<.table id="users" rows={@users}>
  <:col :let={user} label="Name">{user.name}</:col>
  <:col :let={user} label="Email">{user.email}</:col>
  <:col :let={user} label="">
    <.button size="xs" variant="outline" phx-click="edit" phx-value-id={user.id}>
      Edit
    </.button>
  </:col>
</.table>
```

### Data table (sortable, paged, filtered - the full surface)

For anything beyond a static table, reach for `<.data_table>` instead of hand-wiring `<.table>` + pagination + inputs. One `DataTable.State` struct drives the whole surface; `Engine.List` runs it over an in-memory list (or run the state against your own query layer).

```heex
<.data_table
  id="orders"
  rows={@rows}
  state={@table}
  on_change="table"
  searchable
  selectable
  selected={@selected}
  row_id={&row_key/1}
  column_toggle
  hidden_columns={@hidden}
  page_size_options={[10, 25, 50]}
>
  <:col :let={o} field={:customer} sortable filterable="text">{o.customer}</:col>
  <:col :let={o} field={:status} filterable="select" options={["paid", "pending", "refunded"]}>
    <.badge size="sm" variant="soft" label={o.status} />
  </:col>
  <:col :let={o} field={:amount} sortable align="right" filterable="number">${o.amount}</:col>
  <:bulk_action :let={ids}>
    <.button size="sm" variant="soft" color="danger" phx-click="archive" phx-value-ids={Enum.join(ids, ",")}>
      Archive {length(ids)}
    </.button>
  </:bulk_action>
</.data_table>
```

The event-mode backend: UI-state ops (selection, column visibility) get their own clauses, and everything else is query state through `State.handle_op/3` (sort/page/search/page_size/filter/clear_filters). Do NOT skip the UI clauses when using `selectable`/`column_toggle` - `handle_op` ignores those ops by design:

Events post STRING values, so keep the `selected` and `hidden` assigns as string lists (`["1", "7"]`, `["amount"]`) - mixing in integers or atoms makes the membership checks below silently miss:

```elixir
def handle_event("table", %{"op" => "select", "id" => id}, socket) do
  {:noreply, update(socket, :selected, fn sel ->
    if id in sel, do: List.delete(sel, id), else: sel ++ [id]
  end)}
end

def handle_event("table", %{"op" => "select_all"}, socket) do
  page_ids = Enum.map(socket.assigns.rows, &row_key/1)
  sel = socket.assigns.selected

  {:noreply,
   assign(socket, :selected,
     if(Enum.all?(page_ids, &(&1 in sel)), do: sel -- page_ids, else: Enum.uniq(sel ++ page_ids))
   )}
end

def handle_event("table", %{"op" => "clear_selection"}, socket),
  do: {:noreply, assign(socket, :selected, [])}

def handle_event("table", %{"op" => "toggle_column", "field" => f}, socket) do
  {:noreply, update(socket, :hidden, fn h ->
    if f in h, do: List.delete(h, f), else: h ++ [f]
  end)}
end

# move_column (reorderable): apply the field/dir delta to YOUR current
# order via the provided helper - race-free under rapid clicks
def handle_event("table", %{"op" => "move_column", "field" => f, "dir" => dir}, socket) do
  fields = [:customer, :status, :amount]
  {:noreply, update(socket, :column_order, &PetalComponents.DataTable.move_column(&1, fields, f, dir))}
end

def handle_event("table", params, socket) do
  state = State.handle_op(socket.assigns.table, params, fields: [:customer, :status, :amount])
  {rows, state} = Engine.List.run(all_orders(), state)
  {:noreply, assign(socket, rows: rows, table: state)}
end

# ONE identity function, used as both the component's row_id and
# select_all's page sweep - they must never disagree. It goes after the last
# handle_event/3 clause: a defp between clauses is a compiler warning.
defp row_key(row), do: to_string(row.id)
```

The snippet uses `State` and `Engine` unqualified, so the LiveView needs `alias PetalComponents.DataTable.{State, Engine}`.

Selection and column visibility are UI state (the clauses above; move them to a separate `on_ui` event if you prefer) - keep them in assigns, never in URLs. For URL-driven tables pass `path` instead of `on_change`: every interaction becomes a patch URL and `State.from_params/2` in `handle_params` is the whole backend. `row_id` must uniquely identify records across all pages.

### Combobox (searchable select, chips, remote search)

Reach for `<.combo_box>` whenever a `<.select>` has more options than someone wants to scroll. It is form-native: the real control is a hidden `<select>` the `PetalComboBox` hook keeps in sync, so changesets, `phx-change` and LiveView form recovery behave exactly as they do for a plain select. Filtering is client-side and dependency-free.

```heex
<.combo_box
  id="country"
  name="country"
  label="Country"
  options={["Australia", "Japan", "Portugal"]}
/>
```

Always pass `label` (or go through `<.field>`, below). It is the control's accessible name - without it the placeholder is all a screen reader has.

Options take the shapes `select` users expect, and groups are `{heading, options}`:

```heex
<.combo_box
  id="city"
  name="city"
  label="City"
  value="syd"
  options={[
    {"Oceania", [{"Sydney", "syd"}, {"Melbourne", "mel", disabled: true}]},
    {"Europe", [{"Lisbon", "lis"}, {"Stockholm", "sto"}]}
  ]}
/>
```

`multiple` turns the control into a chip row - each choice is a removable token, the panel stays open while picking, and Backspace in an empty input removes the last chip. `max_items` caps it; at the cap the unchosen options go inert. The hidden select becomes a `<select multiple>` and the name gains `[]`, so every choice survives the post.

```heex
<.combo_box
  id="tags"
  name="tags"
  label="Tags"
  multiple
  max_items={5}
  value={@tags}
  options={["elixir", "phoenix", "liveview", "ecto"]}
/>
```

For a remote data source, name an event with `remote_options_event_name` (add `remote_options_target={@myself}` from a LiveComponent). Typing pushes the raw search term, debounced, and the reply becomes the option list:

```elixir
def handle_event("search_users", term, socket) do
  results = MyApp.Accounts.search(term) |> Enum.map(&%{text: &1.name, value: &1.id})
  {:reply, %{results: results}, socket}
end
```

In a form, use `<.field type="combobox">` - it brings the label, changeset errors and help text, and forwards every combobox attr:

```heex
<.form :let={f} for={@changeset} phx-change="validate" phx-submit="save">
  <.field
    type="combobox"
    field={f[:country]}
    label="Country"
    help_text="Where the account is billed"
    options={@countries}
    clearable
  />
</.form>
```

One gotcha through `<.field>`: the anatomy attr is `combo_variant`, NOT `variant` (`:variant` already belongs to radio-card there). `combo_variant="trigger"` gives the select-like button whose panel carries the search input - the picker shape, and what the data table's filter editor uses. On the bare `<.combo_box>` the attr is just `variant`.

```heex
<.field type="combobox" field={f[:owner]} label="Owner" combo_variant="trigger" options={@people} />
```

### Alert / inline feedback

```heex
<.alert color="success" heading="Saved">
  Your changes have been saved.
</.alert>
```

### Loading state on a button

```heex
<.button loading={@saving} phx-click="save">Save</.button>
```

## When in doubt

Stop guessing. Call `list_components` to see the full catalogue, then `get_component <name>` for the exact schema before writing HEEx. The MCP exists so you never have to invent component APIs from training data.

## Companion libraries

- **petal_pro** is the production Phoenix SaaS boilerplate built on petal_components. Use it as a reference for real-world composition (auth pages, dashboards, billing UI, tables with filters, etc.).
- **petal-components-mcp** is this rules file's companion - the MCP server that exposes schemas. Source: https://github.com/petalframework/petal-components-mcp.
