# `SaladUI.LiveView`
[🔗](https://github.com/bluzky/salad_ui/blob/main/lib/salad_ui/liveview.ex#L1)

Helper functions for integrating SaladUI components with Phoenix LiveView.

SaladUI components communicate with LiveView in two directions:

## Component events (client → server)

Interactive components expose `on-*` attributes such as `on-open`, `on-close`,
`on-value-changed`, and `on-select`. These attributes map component lifecycle or
interaction events to LiveView handlers.

Event attributes accept either:

- a server event name string, pushed with `pushEventTo/3`
- a `%Phoenix.LiveView.JS{}` command, executed on the component root

```heex
<.sheet
  id="profile-sheet"
  on-open="sheet_opened"
  on-close={JS.push("sheet_closed")}
>
  ...
</.sheet>
```

```elixir
def handle_event("sheet_opened", params, socket) do
  # params include component metadata such as componentId and component
  {:noreply, socket}
end

def handle_event("sheet_closed", _params, socket) do
  {:noreply, socket}
end
```

Components emit their documented client events when state changes or user
interactions occur. Common dialog-like events are `open` and `close`.

## Server commands (server → client)

Use `send_command/4` inside LiveView callbacks to control a component by id.
Commands map to component state-machine transitions or component-specific commands.
Common commands are `"open"`, `"close"`, and `"toggle"`.

```elixir
def handle_event("open_profile", _params, socket) do
  socket = SaladUI.LiveView.send_command(socket, "profile-sheet", "open")
  {:noreply, socket}
end

def handle_event("close_profile", _params, socket) do
  socket = SaladUI.LiveView.send_command(socket, "profile-sheet", "close")
  {:noreply, socket}
end
```

`send_command/4` pushes the LiveView event `"saladui:command"` to the browser.
SaladUI's hook receives it, matches `target` against the component root id, and calls
the component's `handleCommand(command, params)`.

## Client-side commands

Use `SaladUI.JS.dispatch_command/3` when a LiveView JS command should control a
component directly in the browser.

```heex
<.button phx-click={%JS{} |> SaladUI.JS.dispatch_command("open", to: "#profile-sheet")}>
  Open
</.button>
```

This dispatches a DOM event named `"salad_ui:command"` on the target element.

# `send_command`

Send a command from a LiveView process to a SaladUI component.

## Parameters

- `socket` - LiveView socket.
- `component_id` - ID of the target component root.
- `command` - Command or state-machine transition name, such as `"open"`,
  `"close"`, or `"toggle"`.
- `params` - Optional command payload. Defaults to `%{}`.

## Example

```elixir
socket = SaladUI.LiveView.send_command(socket, "dialog", "open")
```

With params:

```elixir
socket = SaladUI.LiveView.send_command(socket, "chart", "update", %{series: data})
```

---

*Consult [api-reference.md](api-reference.md) for complete listing*
