### Clone and Install Petal Components
Source: https://github.com/petalframework/petal_components/blob/main/README.md
Clone the repository, get dependencies, install Tailwind CSS, and start the local development server.
```shell
git clone https://github.com/petalframework/petal_components.git
cd petal_components
mix deps.get
mix tailwind.install
iex -S mix run dev.exs
```
--------------------------------
### Development Setup (Bash)
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Commands to install dependencies and Tailwind, then run the development server for Petal Components.
```bash
# Install
mix deps.get
mix tailwind.install
# Run dev server
iex -S mix run dev.exs
```
--------------------------------
### Basic Modal Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/modal.md
A simple example demonstrating how to open and display a modal with a title and content.
```heex
<.button phx-click={show_modal("simple")}>
Open
<.modal id="simple" title="Hello">
This is a simple modal.
```
--------------------------------
### Verify Installation
Source: https://github.com/petalframework/petal_components/blob/main/rules.md
Run this command to ensure the project compiles cleanly after installation. A successful compilation indicates that petal_components has been correctly integrated.
```sh
mix compile
```
--------------------------------
### Install Tailwind CSS
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Run this command to install Tailwind CSS if it's not already configured.
```bash
mix tailwind.install
```
--------------------------------
### Install Tailwind and Esbuild Binaries
Source: https://github.com/petalframework/petal_components/blob/main/UPGRADE_GUIDE.md
Install the latest binaries for `esbuild` and `tailwind` using their respective `mix` install tasks.
```bash
mix esbuild.install
mix tailwind.install
```
--------------------------------
### Basic Button Usage Example
Source: https://github.com/petalframework/petal_components/blob/main/rules.md
After successful installation, you can test the integration by dropping a simple button component into any HEEx template.
```heex
<.button>Hello
```
--------------------------------
### User Dropdown Menu Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Example of rendering a user dropdown menu with profile, settings, and logout options.
```heex
<.user_dropdown_menu user_email={@current_user.email}>
<:menu_item label="Profile" to={~p"/profile"} />
<:menu_item label="Settings" to={~p"/settings"} />
<:menu_divider />
<:menu_item label="Logout" phx-click="logout" />
```
--------------------------------
### Loading Spinner Usage Examples
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Examples demonstrating how to use the loading spinner component with different states and sizes, and how it integrates with a button component.
```heex
<.spinner show={@loading?} />
<.spinner show={true} size_class="w-4 h-4" />
<.button loading={@saving}>Save
```
--------------------------------
### Simple Static Table Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/table.md
Renders a basic table with predefined columns and data.
```heex
<.table id="users" rows={@users}>
<:col :let={user} label="Name">{user.name}
<:col :let={user} label="Email">{user.email}
<:col :let={user} label="Role">{user.role}
```
--------------------------------
### Install Petal Components
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/README.md
Add the Petal Components dependency to your `mix.exs` file.
```elixir
{:petal_components, "~> 4.0"}
```
--------------------------------
### Install MCP Server
Source: https://github.com/petalframework/petal_components/blob/main/README.md
Use this command to add the Petal Components MCP server to your system.
```sh
# 1. Install the MCP server once
claude mcp add petal --transport http https://mcp.petal.build/mcp
```
--------------------------------
### HEEx Example for Prompt Input Component
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/chat.md
Example of how to use the `prompt_input` component in a HEEx template, customizing the submit event and placeholder.
```heex
```
--------------------------------
### Migration Example: Field Component
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/field.md
This example shows the recommended new syntax for the Field component, migrating from the older 'form_field' helper. It simplifies attribute passing and usage.
```heex
<.form_field form={@form} field={:name} type="text_input" />
```
```heex
<.field field={@form[:name]} type="text" />
```
--------------------------------
### Alert Component Usage Examples
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Examples showing how to use the alert component with different colors, titles, icons, and dismissal settings.
```heex
<.alert color="success" title="Success!" icon="hero-check-circle">
Your changes have been saved.
<.alert color="danger" icon="hero-exclamation-circle" dismissible={true}>
An error occurred. Please try again.
```
--------------------------------
### Push Event Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Example of pushing an event from the server to the client JavaScript in LiveView. Used for real-time communication.
```elixir
# Push event (server -> client JS)
push_event(socket, "pc-chat-token", %{id: "msg1", text: "Hello"})
```
--------------------------------
### Handle Event Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Example of handling an event sent from the client to the server in LiveView. This function processes incoming client events.
```elixir
# Handle event (client -> server)
def handle_event("send_message", params, socket) do
# params = %{"prompt" => "..."}
{:noreply, socket}
end
```
--------------------------------
### CSS Selector Examples
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Provides examples of CSS selectors for targeting elements. Supports ID, class, attribute, and combined selectors.
```elixir
# ID selector
"#modal-1"
# Class selector
".pc-modal"
# Attribute selector
"[data-id='123']"
# Combined
".pc-modal#main-modal"
```
--------------------------------
### Install Optional Dependency
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/chat.md
Add the `mdex` dependency to your `mix.exs` file for markdown rendering.
```elixir
{:mdex, "~> 0.12"}
```
--------------------------------
### Elixir Example for Streaming Markdown
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/chat.md
Example of handling streamed markdown content in a LiveView, converting buffer content to HTML and pushing it as an event.
```elixir
def handle_info({:stream_markdown, buffer}, socket) do
html = PetalComponents.Chat.to_html(buffer)
{:noreply, push_event(socket, "pc-chat-token", %{id: "answer", html: html})}
end
```
--------------------------------
### Button Group Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Example of grouping related buttons together using the ButtonGroup component.
```heex
<.button_group>
<.button variant="outline">Left
<.button variant="outline">Middle
<.button variant="outline">Right
```
--------------------------------
### Avatar Component Examples
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Shows how to use the Avatar component with an image source and name, and how to use the avatar_group component with a list of avatars and a maximum display count.
```heex
<.avatar src="https://example.com/user.jpg" name="John Doe" />
<.avatar_group
avatars={[
%{src: "user1.jpg", name: "User 1"},
%{src: "user2.jpg", name: "User 2"}
]}
max_display={3}
/>
```
--------------------------------
### Using Phoenix.LiveView.JS for UI Interactions
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Examples demonstrating the use of Phoenix.LiveView.JS for common UI interactions like opening modals or navigating the page.
```heex
<.modal on_open={JS.show()} />
<.button phx-click={JS.navigate(~p"/home")} />
```
--------------------------------
### Phoenix.LiveView.JS Event Examples
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Examples of using the Phoenix.LiveView.JS module for client-side interactions. These functions simulate user actions or trigger JavaScript events.
```elixir
JS.click() # Simulate click
JS.show() # Show element
JS.hide() # Hide element
JS.navigate(path) # Navigate
JS.push(event) # Push event
JS.dispatch(...) # Dispatch custom event
```
--------------------------------
### Container Component Usage Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Demonstrates using the container component to wrap content with a specified size and custom classes for layout.
```heex
<.container size="lg" class="mx-auto py-8">
Content
```
--------------------------------
### Setup Assets for Petal Components
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/README.md
Import necessary Tailwind CSS and Petal Components assets into your `assets/css/app.css` file.
```css
@import "tailwindcss";
@source "../deps/petal_components/**/*.*ex";
@import "../deps/petal_components/assets/default.css";
```
--------------------------------
### Icon Component Usage Examples
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Demonstrates how to use the Icon component with different Heroicon names and sizes. Ensure Heroicon names are prefixed with 'hero-' or 'hero-*-solid'.
```heex
<.icon name="hero-check" size="md" />
<.icon name="hero-chevron-right" class="text-blue-500" />
<.icon name="hero-arrow-down" size="lg" />
```
--------------------------------
### Modal with Form Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/modal.md
Demonstrates integrating a form within a modal. This is useful for user input and data submission.
```heex
<.button phx-click={show_modal("edit_user")}>
Edit User
<.modal id="edit_user" title="Edit User" max_width="lg">
<.form for={@form} phx-submit="update_user">
<.field field={@form[:name]} />
<.field field={@form[:email]} type="email" />
<.button type="submit">Save
```
--------------------------------
### Badge Component Examples
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Demonstrates how to use the Badge component with different colors and variants. Supports 'solid', 'light', and 'outline' variants.
```heex
<.badge color="success">Active
<.badge color="danger" variant="outline">Draft
<.badge color="info">v1.0
```
--------------------------------
### Pagination Component Usage Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Demonstrates how to use the Pagination component with specific page and total page numbers, and custom link type and path.
```heex
<.pagination
current_page={@page}
total_pages={@total_pages}
link_type="live_patch"
path={~p"/products?page=:page"}
/>
```
--------------------------------
### Skeleton Component Usage Examples
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Shows various ways to use the Skeleton component, including different variants, dimensions, and counts.
```heex
<.skeleton variant="text" />
<.skeleton variant="circle" width="40px" height="40px" />
<.skeleton count={3} />
```
--------------------------------
### Component Testing (Elixir)
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Example of how to test components using Phoenix.LiveViewTest in an ExUnit test case.
```elixir
defmodule MyAppWeb.ComponentTest do
use ExUnit.Case
import Phoenix.LiveViewTest
test "button renders with text" do
rendered = render_component(&button/1, label: "Click me")
assert rendered =~ "Click me"
end
end
```
--------------------------------
### Confirmation Modal Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/modal.md
Shows a confirmation modal with a destructive action (delete) and a cancel option. Includes buttons for both actions.
```heex
<.button color="danger" phx-click={show_modal("confirm_delete")}>
Delete
<.modal id="confirm_delete" title="Confirm Delete" max_width="sm">
Are you sure? This cannot be undone.
<.button
color="danger"
phx-click="confirm_delete"
phx-click={hide_modal("confirm_delete")}
>
Delete
<.button variant="outline" phx-click={hide_modal("confirm_delete")}>
Cancel
```
--------------------------------
### Table with Row Actions HEEx Example
Source: https://github.com/petalframework/petal_components/blob/main/rules.md
Illustrates creating a table with columns for data and a final column for row-specific actions like editing. Each row can have interactive buttons.
```heex
<.table>
<:col :let={user} label="Name">{user.name}
<:col :let={user} label="Email">{user.email}
<:col :let={user} label="">
<.button size="xs" variant="outline" phx-click="edit" phx-value-id={user.id}>
Edit
```
--------------------------------
### Alert / Inline Feedback HEEx Example
Source: https://github.com/petalframework/petal_components/blob/main/rules.md
Provides an example of displaying an alert message with a success status and a heading. Use for providing immediate feedback to the user.
```heex
<.alert color="success" heading="Saved">
Your changes have been saved.
```
--------------------------------
### Table with Row Actions
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/overview.md
Example of rendering a table with user data, including columns for name and email, and a dedicated column for row-specific actions like an 'Edit' button.
```heex
<.table rows={@users} id="users-table">
<:col :let={user} label="Name">{user.name}
<:col :let={user} label="Email">{user.email}
<:col :let={user} label="">
<.button size="xs" variant="outline" phx-click="edit" phx-value-id={user.id}>
Edit
```
--------------------------------
### Breadcrumbs Component Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Illustrates the usage of the Breadcrumbs component, passing a list of items defined in the `@breadcrumb_items` assign.
```heex
<.breadcrumbs items={@breadcrumb_items} />
```
--------------------------------
### Select Input with Prompt
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/field.md
Renders a select dropdown with a default prompt option. Use to guide user selection.
```heex
<.field
field={@form[:category]}
type="select"
prompt="Choose a category"
options={[{"Option 1", "val1"}]}
/>
```
--------------------------------
### HEEx Example for Markdown Component
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/chat.md
Demonstrates using the `markdown` component within a `chat_message` component to display assistant responses.
```heex
```
--------------------------------
### Menu Component Usage
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Example of creating a customizable menu structure with navigation links and dividers. Use for site navigation or action menus.
```heex
<.menu id="main-menu">
<.menu_item to="/" label="Home" />
<.menu_item to="/about" label="About" />
<.menu_divider />
<.menu_item to="/contact" label="Contact" />
```
--------------------------------
### Link Component Usage Examples
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Shows how to use the Link component for different link types: standard anchor, LiveView patch, and button clicks. Specify `link_type` and `to` or `phx-click` as needed.
```heex
<.a to="/" link_type="a">Home
<.a to={~p"/dashboard"} link_type="live_patch">Dashboard
<.a link_type="button" phx-click="delete">Delete
```
--------------------------------
### LiveView Stream Integration for Tables
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/table.md
Use LiveView streams to efficiently update large tables. This example shows how to define the table structure and handle stream updates in the LiveView module.
```heex
<.table
id="users"
rows={@streams.users}
row_id={fn {id, _user} -> id end}
>
<:col :let={_user_id, user} label="Name">{user.name}
<:col :let={_user_id, user} label="Email">{user.email}
<:col :let={_user_id, user} label="Actions" class="w-20">
<.button size="xs" phx-click="delete" phx-value-id={user.id}>
Delete
```
--------------------------------
### HEEx Example for Tool Call Component
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/chat.md
Shows how to use the `tool_call` component to display a completed tool call with associated content, like a weather card.
```heex
<.weather_card city="San Francisco" temp="72°F" />
```
--------------------------------
### Use LiveView Streams for Large Lists
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Utilize LiveView streams for rendering large lists or tables efficiently. This example shows how to set up a stream in your LiveView mount function.
```heex
<.table rows={@streams.users}>
<:col :let={_id, user} label="Name">{user.name}
```
```elixir
def mount(_params, _session, socket) do
{:ok, stream(socket, :users, query_users())}
end
```
--------------------------------
### Accordion Component Usage
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Example of how to use the Accordion component with entries and custom item headings. Supports variants and multiple open items.
```heex
<.accordion entries={@faq_items} variant="ghost" multiple={true}>
<:item :for={{item, idx}} heading={item.question}>
{item.answer}
```
--------------------------------
### Progress Component Usage
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Examples of how to use the progress component with different attributes. The `value` attribute is required, while `label`, `color`, and `size` are optional.
```heex
<.progress value={65} label="Loading..." />
```
```heex
<.progress value={100} color="success" size="lg" />
```
--------------------------------
### Dropdown Component Usage
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Example of using the Dropdown component with a button as a trigger and custom menu items. Supports click handlers.
```heex
<.dropdown id="menu">
<:trigger_element>
<.button variant="outline">Menu
<.dropdown_menu_item label="Edit" phx-click="edit" />
<.dropdown_menu_item label="Delete" phx-click="delete" color="danger" />
```
--------------------------------
### Stepper Component Usage
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Example of how to render the stepper component with specified steps and current step. The `clickable` attribute controls whether steps can be clicked.
```heex
<.stepper
steps={["Account", "Details", "Confirmation"]}
current_step={@step}
clickable={false}
/>
```
--------------------------------
### Tabs Component Usage
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Example of rendering a tabs component with multiple tab items. Each tab requires a `label` attribute.
```heex
<.tabs id="settings" active_tab="account">
<:tab label="Account">
Account settings
<:tab label="Privacy">
Privacy settings
<:tab label="Notifications">
Notification settings
```
--------------------------------
### Range Dual Slider Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/field.md
Configures a dual range slider for price filtering with custom labels and a prefix. The form submits on 'filter'.
```heex
<.form for={@form} phx-submit="filter">
<.field
min_field={@form[:price_min]}
max_field={@form[:price_max]}
type="range-dual"
range_min={0}
range_max={10000}
range_min_label="Minimum"
range_max_label="Maximum"
value_prefix="$"
help_text="Select price range"
/>
<.button type="submit">Apply Filter
```
--------------------------------
### Responsive Card Layout
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/card.md
Create a responsive card layout where the media and content sections adjust their width and display based on screen size. This example uses Tailwind CSS's responsive prefixes.
```heex
<.card class="sm:flex sm:flex-row">
<.card_media class="sm:w-1/3">
<.card_content class="sm:w-2/3">
{@item.name}
{@item.description}
```
--------------------------------
### Set up Component Testing
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Define a `ComponentCase` module using `ExUnit.CaseTemplate` to import necessary Phoenix and PetalComponents testing functions.
```elixir
defmodule MyAppWeb.ComponentCase do
use ExUnit.CaseTemplate
using do
quote do
import Phoenix.Component
import Phoenix.LiveViewTest
import PetalComponents
end
end
end
```
--------------------------------
### NumberTicker Component
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/core-components.md
Displays an animated counter. Configure the start, end, and direction of the number animation.
```heex
<.number_ticker from="0" to="100" direction="up" />
```
--------------------------------
### Fetch Dependencies
Source: https://github.com/petalframework/petal_components/blob/main/rules.md
Run this command in your terminal to fetch all project dependencies after updating `mix.exs`.
```sh
mix deps.get
```
--------------------------------
### Audit Accessibility
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Run this Mix task to audit the accessibility of your components, assuming the a11y_audit library is installed.
```bash
# Mix tasks (if a11y_audit is installed)
mix a11y.audit
```
--------------------------------
### Simple Options List
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
A basic list of tuples for options, where each tuple contains a display string and a corresponding value.
```elixir
[{"Option 1", "opt1"}, {"Option 2", "opt2"}]
```
--------------------------------
### Tailwind Customization (CSS)
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Example of customizing Tailwind CSS colors using CSS variables in `assets/css/app.css`.
```css
/* assets/css/app.css */
@layer theme {
--color-primary: #3b82f6;
--color-danger: #ef4444;
}
```
--------------------------------
### Using Phoenix.HTML.FormField in a Component
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Example of how to use a Phoenix.HTML.FormField struct within a component, automatically extracting data from a form field.
```heex
<.field field={@form[:email]} />
```
--------------------------------
### Add Tailwind CSS Plugins
Source: https://github.com/petalframework/petal_components/blob/main/UPGRADE_GUIDE.md
Includes the typography and forms plugins for enhanced styling capabilities. Ensure these plugins are installed in your project.
```css
@plugin "@tailwindcss/typography";
@plugin "@tailwindcss/forms";
```
--------------------------------
### Import Petal Components in Web Module
Source: https://github.com/petalframework/petal_components/blob/main/rules.md
Include `use PetalComponents` within the `quote do` block of your `html` macro in `lib/_web.ex` (or umbrella equivalent) to make components available as HEEx tags.
```elixir
use Phoenix.Component
use PetalComponents
# ... existing imports
```
--------------------------------
### Standard Phoenix Dockerfile
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
A standard Phoenix Dockerfile that includes steps for dependency retrieval, asset deployment, and release compilation.
```dockerfile
FROM hexpm/elixir:latest
WORKDIR /app
COPY . .
RUN mix deps.get && mix assets.deploy && mix release
CMD ["./bin/myapp", "start"]
```
--------------------------------
### Project File Structure
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/README.md
Overview of the directory structure for the Petal Components documentation and reference files.
```text
/workspace/home/output/
├── REFERENCE.md ← Master reference guide
├── INDEX.md ← Index (this file)
├── README.md ← You are here
├── types.md ← Type definitions
├── configuration.md ← Setup & config
└── api-reference/
├── overview.md ← Project overview
├── button.md ← Button component
├── field.md ← Form field
├── modal.md ← Modal dialog
├── table.md ← Data table
├── card.md ← Card container
├── chat.md ← Chat interface
├── form-components.md ← Form helpers
└── core-components.md ← Other components
```
--------------------------------
### Set up JavaScript Hooks for Petal Components
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Import Petal Components JavaScript and include its hooks in your LiveSocket configuration in `assets/js/app.js`. This enables features like password toggles, copy-to-clipboard, and chat streaming.
```javascript
import PetalComponents from "../../deps/petal_components/assets/js/petal_components"
const liveSocket = new LiveSocket("/live", Socket, {
params: { _csrf_token: csrfToken },
hooks: { ...PetalComponents },
})
liveSocket.connect()
export default liveSocket
```
--------------------------------
### Modal with Multiple Sections (Wizard)
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/modal.md
Implement multi-step modals by conditionally rendering content based on a state variable (e.g., `@step`) and using navigation buttons.
```heex
<.modal id="wizard" title="Setup Wizard" max_width="lg">
<%= case @step do %>
<% 1 -> %>
Step 1: Account
Enter your account details
<% 2 -> %>
Step 2: Preferences
Choose your preferences
<% end %>
<.button
:if={@step > 1}
variant="outline"
phx-click="prev_step"
>
Back
<.button
color="primary"
phx-click={if @step < 2, do: "next_step", else: "finish"}
>
<%= if @step < 2, do: "Next", else: "Finish" %>
\.modal>
<.button phx-click={show_modal("wizard")}>
Start Setup
```
--------------------------------
### Class Types for Components (String and List)
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Demonstrates how to apply CSS classes to components using either a single string or a list of strings. Lists are automatically joined.
```elixir
# String
class="text-center font-bold"
# List (automatically joined)
class={[ "text-center", @active? && "font-bold" ]}
# Conditional
class={[ @base_class, @active? && @active_class ]}
```
--------------------------------
### Import Petal Components into Web Module
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Use the `PetalComponents` macro within your `MyAppWeb` module's `html/1` function to import all core components, making them available in your templates.
```elixir
defmodule MyAppWeb do
def html do
quote do
use PetalComponents
# ... your other imports
end
end
end
```
--------------------------------
### Create Test Fixtures
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Define a `Support.Fixtures` module to create mock data, such as a `user_fixture`, for use in tests.
```elixir
defmodule Support.Fixtures do
def user_fixture(attrs \ %{}) do
Map.merge(%{
id: 1,
name: "John Doe",
email: "john@example.com"
}, attrs)
end
end
```
--------------------------------
### Form Field Migration (v3.x)
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/form-components.md
Example of the older `form_field` component usage in Petal Components v3.x. This pattern is now deprecated in favor of the `Field` component.
```heex
<.form_field
form={@form}
field={:email}
type="email_input"
label="Email Address"
help_text="We'll never share your email"
/>
```
--------------------------------
### Get Default JS Library (Elixir)
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Retrieves the default JavaScript library used by Petal Components. This is deprecated in v4.0+ and always returns 'live_view_js'.
```elixir
defmodule PetalComponents do
@default_js_lib Application.compile_env(:petal_components, :default_js_lib, "live_view_js")
def default_js_lib() do
@default_js_lib
end
end
```
--------------------------------
### Get Default JavaScript Library
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/overview.md
Retrieve the name of the default JavaScript library used by Petal Components. This is deprecated in v4.0+ and always returns 'live_view_js'.
```elixir
PetalComponents.default_js_lib() # returns "live_view_js"
```
--------------------------------
### Basic Select Input
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/field.md
Renders a basic select dropdown. Requires `options` to be a list of tuples.
```heex
<.field
field={@form[:category]}
type="select"
options={[{"Option 1", "val1"}, {"Option 2", "val2"}]}
/>
```
--------------------------------
### Phoenix Form Struct Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Represents the structure of a Phoenix HTML form, used in form building. It contains details about the changeset, implementation, and form attributes.
```elixir
%Phoenix.HTML.Form{
source: changeset,
impl: impl,
id: "user_form",
name: :user,
params: map(),
hidden: [...]
}
```
--------------------------------
### Using Form Components with Phoenix Forms
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/form-components.md
Demonstrates how to integrate Petal Components' form elements within a Phoenix form. It shows the recommended `<.field>` component alongside older or raw input methods.
```heex
<.form for={@form} phx-submit="save">
<.form_field form={@form} field={:email} type="email_input" />
<.text_input
name={Phoenix.HTML.Form.input_name(@form, :email)}
value={Phoenix.HTML.Form.input_value(@form, :email)}
/>
<.field field={@form[:email]} type="email" />
```
--------------------------------
### Configure Web Module for Petal Components
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/README.md
Configure your web module to use Petal Components by quoting the `use PetalComponents` statement.
```elixir
def html do
quote do
use PetalComponents
end
end
```
--------------------------------
### Render Table with Actions
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/REFERENCE.md
Create an interactive table using the `<.table>` component. Define columns with `<:col>` and include action buttons within a column.
```heex
<.table rows={@users} id="users-table">
<:col :let={user} label="Name">{user.name}
<:col :let={user} label="Email">{user.email}
<:col :let={user} label="">
<.button size="xs" phx-click="edit" phx-value-id={user.id}>Edit
```
--------------------------------
### Form within a Card Component
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/overview.md
Example of embedding a form inside a card component for structured input. Use the `<.form>` and `<.field>` components for input elements.
```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
```
--------------------------------
### Compile Assets for Production
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Run this command to compile Tailwind CSS, minimize JavaScript, remove unused CSS, and create asset manifests for production.
```bash
mix assets.deploy
```
--------------------------------
### Configure MCP Server
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Add the MCP server for AI assistant integration using the `claude mcp add` command. This exposes component management APIs.
```bash
claude mcp add petal --transport http https://mcp.petal.build/mcp
```
--------------------------------
### Project Documentation Structure
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/REFERENCE.md
This snippet shows the directory structure for the Petal Components project documentation. It highlights the main reference file and the organization of API-specific documentation.
```text
/workspace/home/output/
├── REFERENCE.md # This file
├── types.md # Type definitions
├── configuration.md # Setup & config
├── api-reference/
│ ├── overview.md # Project overview & imports
│ ├── button.md # Button component
│ ├── field.md # Field component (forms)
│ ├── modal.md # Modal component
│ ├── table.md # Table component
│ ├── card.md # Card component
│ ├── chat.md # Chat component
│ ├── form-components.md # Form helpers
│ └── core-components.md # Other components
```
--------------------------------
### Ecto Changeset Struct Example
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
The structure of an Ecto changeset, used for form validation and data manipulation. It includes validity status, errors, changes, and the associated schema data.
```elixir
%Ecto.Changeset{
valid?: boolean,
errors: [{field, {message, []}}, ...],
changes: map,
data: schema
}
```
--------------------------------
### Add Heroicons Dependency and Import
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Ensure Heroicons are listed in your `mix.exs` dependencies and imported in your web module.
```elixir
# mix.exs should have:
{:heroicons, ...}
# And imported in web module:
alias PetalComponents.HeroiconsV1
```
--------------------------------
### Date Literal and Function
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Represents date values using Elixir's literal format or a function to get the current date. Ensure correct formatting for date literals.
```elixir
~D[2024-01-15] # Elixir date literal
Date.utc_today()
```
--------------------------------
### DateTime Literal and Function
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Represents combined date and time values using Elixir's literal format or a function to get the current datetime. ISO 8601 format is used for literals.
```elixir
~U[2024-01-15T14:30:00Z] # Elixir datetime literal
DateTime.utc_now()
```
--------------------------------
### Time Literal and Function
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/types.md
Represents time values using Elixir's literal format or a function to get the current time. Time literals follow HH:MM:SS format.
```elixir
~T[14:30:00] # Elixir time literal
Time.utc_now()
```
--------------------------------
### Basic Button Usage
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/button.md
Renders a simple clickable button with the text 'Click me'.
```heex
<.button>Click me
```
--------------------------------
### Transform Row Data with row_item
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/table.md
Use the `row_item` function to transform data before it's rendered in table cells. This is useful for accessing nested data or performing calculations. The example shows calculating a total from nested items.
```heex
<.table
id="orders"
rows={@orders}
row_item={fn order -> %{order: order, total: order.items |> Enum.sum(& &1.price)} end}
>
<:col :let={data} label="Order ID">{data.order.id}
<:col :let={data} label="Customer">{data.order.customer.name}
<:col :let={data} label="Total">${data.total}
```
--------------------------------
### Form Field Migration (v4.0+)
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/form-components.md
Example of the new `Field` component usage in Petal Components v4.0+. This component simplifies form field rendering by automatically handling value extraction, error display, and help text.
```heex
<.field
field={@form[:email]}
type="email"
label="Email Address"
help_text="We'll never share your email"
/>
```
--------------------------------
### Run Petal Components Tests
Source: https://github.com/petalframework/petal_components/blob/main/README.md
Execute the test suite for the Petal Components project.
```shell
mix test
```
--------------------------------
### Customize Color Palette with CSS Variables
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Define custom color variables in your app.css file to override the default component color palette. This example shows setting primary and success colors for both light and dark modes.
```css
:root {
--pc-primary: #3b82f6;
--pc-success: #10b981;
--pc-danger: #ef4444;
--pc-warning: #f59e0b;
--pc-info: #0ea5e9;
}
@media (prefers-color-scheme: dark) {
:root {
--pc-primary: #60a5fa;
--pc-success: #34d399;
}
}
```
--------------------------------
### Button with Loading State
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/button.md
Use this snippet to display a button that shows a loading spinner when a process is active. The `.pc-button--loading` class is automatically applied.
```heex
<.button loading={@saving} phx-click="save">
Save
```
--------------------------------
### Integrate Petal Components JS Hooks
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/configuration.md
Import PetalComponents from its path and include it in your LiveSocket options' hooks.
```javascript
import PetalComponents from "../../deps/petal_components/assets/js/petal_components"
// In LiveSocket options:
hooks: { ...PetalComponents }
```
--------------------------------
### Conditional Rendering in Table Cells
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/table.md
Conditionally render content within table cells based on data. This example shows displaying different badge components for task completion status and conditionally rendering a 'Mark Done' button.
```heex
<.table id="tasks" rows={@tasks}>
<:col :let={task} label="Title">{task.title}
<:col :let={task} label="Status">
<%= if task.completed do %>
<.badge color="success">Done
<% else %>
<.badge color="info">In Progress
<% end %>
<:col :let={task} label="Actions">
<.button
:if={!task.completed}
size="xs"
phx-click="complete"
phx-value-id={task.id}
>
Mark Done
```
--------------------------------
### Table with Pagination
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/api-reference/table.md
Integrate pagination with the table component. Ensure you have a pagination component available and configure it with the current page, total pages, and path.
```heex
<.table id="paginated" rows={@users}>
<:col :let={user} label="Name">{user.name}
<.pagination
current_page={@page}
total_pages={@total_pages}
link_type="live_patch"
path={~p"/users?page=:page"}
/>
```
--------------------------------
### Consistent Styling Attributes for Button-like Components
Source: https://github.com/petalframework/petal_components/blob/main/_autodocs/REFERENCE.md
Button-like components, including buttons and badges, share consistent styling attributes such as `size`, `color`, and `variant`. Example shows 'lg' size, 'danger' color, and 'outline' variant for a button.
```heex
<.button size="lg" color="danger" variant="outline" />
<.badge size="lg" color="danger" />
<.badge size="lg" color="danger" />
```