# 10. Surfaces in a Phoenix app

Macaw needs no framework, router or database of its own: any Phoenix app renders a
surface with one call. This chapter puts the pieces from the earlier chapters into a
Phoenix 1.8 app: configuring the registry once, mapping source names per request,
rendering from a controller and from a LiveView, and serving the stylesheets.

**What you'll learn:**

- where the configuration, sources and documents live in an app;
- rendering a surface with `Macaw.Surface.show/2` in a controller template and in a
  LiveView;
- choosing the rendering mode from the LiveView's socket;
- serving the layout, table and theme stylesheets under a strict Content Security Policy;
- what the live runtime, not yet released, will add.

The code assumes an app generated by `mix phx.new my_app`, with `phoenix_live_view`, and
the sources and components from chapters 1 to 6.

## Configuration

What every surface in the app shares goes in your app's own configuration, in
`config/config.exs`: the component packages documents may use (`Macaw.Builtin` is always
among them), any layouts you add, and the row ceiling. Macaw reads no configuration of
its own, as no Macaw library reads the application environment: your app reads it and
passes what Macaw needs.

```
import Config

config :my_app, :macaw,
  packages: [MyApp.Components],
  ceiling: 1_000
```

`Macaw.Registry.from_config/1` builds a registry from such a list, answering
`{:ok, registry}` or the configuration's faults. Build it once from your application's
`start/2`, before the endpoint starts, with its `!` twin, so a misconfigured package fails
the boot rather than the first request, and keep it where your app keeps such things:

```elixir
defmodule MyApp.Boot do
  @moduledoc "What `MyApp.Application.start/2` runs before its children."

  @doc "Builds the app's registry from its configuration and keeps it."
  def macaw! do
    registry = Macaw.Registry.from_config!(config())
    :persistent_term.put({__MODULE__, :registry}, registry)
    registry
  end

  @doc "The registry `macaw!/0` built."
  def registry, do: :persistent_term.get({__MODULE__, :registry})

  @doc "The most rows any slot may receive."
  def ceiling, do: Keyword.fetch!(config(), :ceiling)

  defp config, do: Application.fetch_env!(:my_app, :macaw)
end
```

A session without the file sets the same key, then boots:

```elixir
Application.put_env(:my_app, :macaw, packages: [MyApp.Components], ceiling: 1_000)

MyApp.Boot.macaw!() |> Macaw.Registry.packages()
#=> [Macaw.Builtin, MyApp.Components]
```

## A dashboards module

Keep everything Macaw-specific behind one module of your app. It maps document source
names to configured sources, holds the documents, and shows them for a viewer:

```elixir
defmodule MyApp.Dashboards do
  @moduledoc "The app's surfaces: the sources, the documents, and showing them."

  alias Macaw.Surface

  @doc "The sources documents may name, configured for this app."
  def sources do
    %{
      "services" => {%MyApp.Services{}, nil},
      "latency" => {%MyApp.Latency{}, nil}
    }
  end

  @doc "The status surface. A real app might read it from a store (chapter 8)."
  def status do
    Surface.build!("status",
      title: "Service status",
      cells: [
        {"my_app.stat",
         name: "errors",
         settings: %{"label" => "Errors"},
         place: %{x: 0, y: 0, w: 4, h: 2},
         source: "services",
         fields: %{"value" => "errors"}},
        {"macaw.table",
         name: "services",
         settings: %{"caption" => "Services", "sort" => "p50", "order" => "desc"},
         place: %{x: 4, y: 0, w: 8, h: 4},
         source: "services"}
      ]
    )
  end

  @doc """
  Shows a surface for a viewer: `{:ok, safe_html}` or `{:error, faults}`. `opts` are
  `Macaw.Surface.show/2`'s: `socket:` for a LiveView's mode, `now:`, `theme:`, …
  """
  def show(surface, viewer, opts \\ []) do
    env = [sources: sources(), viewer: viewer, registry: MyApp.Boot.registry(), ceiling: MyApp.Boot.ceiling()]
    Surface.show(surface, env ++ opts)
  end
end
```

`show/2` does the rest: it validates against the registry it is given, holds each slot
to the ceiling, and fetches and renders. The clock is read once, in that call, on
the host's side, and every source and component on the surface sees that one instant. A
test passes its own `now:`, so its output never depends on the clock:

```elixir
now = ~U[2026-10-29 12:00:30Z]
{:ok, html} = MyApp.Dashboards.show(MyApp.Dashboards.status(), %{id: 1}, now: now)

Phoenix.HTML.safe_to_string(html) =~ ~s(<div class="mw-surface" id="status">)
#=> true
```

Faults come back as values, so a page can show them to whoever can fix the document:

```elixir
{:ok, typo} = Macaw.Surface.new(name: "typo", cells: %{"x" => %{component: "macaw.tabel", place: %{x: 0, y: 0, w: 1, h: 1}}})
MyApp.Dashboards.show(typo, nil, now: now)
#=> {:error, [{[:cells, "x", :component], {:unknown_component, "macaw.tabel"}}]}
```

## In a controller

A surface renders to a `Phoenix.HTML` safe value, which a HEEx template outputs as it is:

```elixir
defmodule MyAppWeb.StatusController do
  use MyAppWeb, :controller

  def show(conn, _params) do
    case MyApp.Dashboards.show(MyApp.Dashboards.status(), conn.assigns[:current_user]) do
      {:ok, surface} -> render(conn, :show, surface: surface)
      {:error, faults} -> conn |> put_status(500) |> text(Enum.map_join(faults, "\n", &Macaw.Base.Fault.format/1))
    end
  end
end

defmodule MyAppWeb.StatusHTML do
  use MyAppWeb, :html

  def show(assigns) do
    ~H"""
    <main class="mw-theme-auto">
      {@surface}
    </main>
    """
  end
end
```

Route it as usual, `get "/status", StatusController, :show`. The `mw-theme-auto` class
picks the light or dark theme from the viewer's preference (chapter 9). The template
renders:

```elixir
{:ok, surface} = MyApp.Dashboards.show(MyApp.Dashboards.status(), nil, now: now)

%{surface: surface}
|> MyAppWeb.StatusHTML.show()
|> Phoenix.HTML.Safe.to_iodata()
|> IO.iodata_to_binary()
|> String.starts_with?(~s(<main class="mw-theme-auto">\n  <div class="mw-surface" id="status">))
#=> true
```

## In a LiveView

A LiveView renders the surface in `mount/3`. Its first, disconnected render is plain
HTML, `:socketless`; once connected, `:live`. Pass the socket as `socket:` and `show/2`
picks the mode from it, as `Phoenix.LiveView.connected?/1` would:

```elixir
defmodule MyAppWeb.StatusLive do
  use MyAppWeb, :live_view

  @impl true
  def mount(_params, _session, socket) do
    case MyApp.Dashboards.show(MyApp.Dashboards.status(), socket.assigns[:current_user], socket: socket) do
      {:ok, surface} -> {:ok, assign(socket, surface: surface, faults: [])}
      {:error, faults} -> {:ok, assign(socket, surface: nil, faults: faults)}
    end
  end

  @impl true
  def render(assigns) do
    ~H"""
    <main class="mw-theme-auto">
      {@surface}
      <ul :if={@faults != []}>
        <li :for={fault <- @faults}>{Macaw.Base.Fault.format(fault)}</li>
      </ul>
    </main>
    """
  end
end
```

```elixir
{:ok, socket} = MyAppWeb.StatusLive.mount(%{}, %{}, %Phoenix.LiveView.Socket{})

socket.assigns
|> MyAppWeb.StatusLive.render()
|> Phoenix.HTML.Safe.to_iodata()
|> IO.iodata_to_binary()
|> String.contains?(~s(id="status-services"))
#=> true
```

Route it with `live "/status", StatusLive`. To refresh, re-render on a timer or a PubSub
message and assign the new value. The components' own events (the table's sort buttons)
reach the LiveView's `handle_event("mw-event", params, socket)`: read each with
`Macaw.State.event/3`, apply it with `Macaw.State.apply/2`, and render at the new state,
as chapter 4's `SortedLive` does; keep the state across reloads with
`Macaw.State.persist/3` and `restore/3` in `handle_params/3` (chapter 4, "Keeping state
in the URL"). Change notification, re-fetching only what changed and per-cell processes
are `macaw_live`'s, the runtime still to come.

## Serving the stylesheets

A surface needs static stylesheets: its layout's, the table's, and your themes'. Each is
a pure function of the code (an areas layout's, of its template too), served at its
content address under `/assets/`, which `Plug.Static` already serves from
`priv/static/assets` in a generated app. `Macaw.Surface.stylesheet/1` gives a validated
surface's layout sheet as `{path, css}`, so one small module can list every sheet the
app's surfaces need:

```elixir
defmodule MyApp.Styles do
  @moduledoc "The stylesheets the app's surfaces need, each `{path, css}`."
  alias Macaw.Layers.Theme

  def all do
    {:ok, status} = Macaw.Surface.validate(MyApp.Dashboards.status(), MyApp.Boot.registry(), MyApp.Dashboards.sources())
    Enum.uniq([Macaw.Surface.stylesheet(status), table(), themes()])
  end

  def paths, do: Enum.map(all(), &elem(&1, 0))

  defp table, do: {Macaw.Builtin.Table.stylesheet_path(), Macaw.Builtin.Table.stylesheet()}

  defp themes do
    {:ok, css} = Theme.Sheet.stylesheet([Theme.default(), Theme.dark()], auto: {Theme.default(), Theme.dark()})
    {Macaw.Component.Stylesheet.path(css), css}
  end
end
```

Write them at build time with a Mix task:

```elixir
defmodule Mix.Tasks.MyApp.MacawAssets do
  @shortdoc "Writes the stylesheets Macaw's surfaces need to priv/static"
  @moduledoc "Writes the layout, table and theme stylesheets at their content addresses."
  use Mix.Task

  @impl true
  def run(_args) do
    Mix.Task.run("app.config")

    for {path, css} <- MyApp.Styles.all() do
      file = Path.join("priv/static", path)
      File.mkdir_p!(Path.dirname(file))
      File.write!(file, css)
      Mix.shell().info("wrote #{path}")
    end
  end
end
```

```elixir
Mix.Tasks.MyApp.MacawAssets.run([])
Enum.all?(MyApp.Styles.paths(), &File.exists?(Path.join("priv/static", &1)))
#=> true
```

Then link them from your root layout, `root.html.heex`, next to your app's own CSS:

```heex
<link :for={path <- MyApp.Styles.paths()} rel="stylesheet" href={path} />
```

Because the paths are content addresses, you can cache them forever: a changed
stylesheet has a new path.

If your components' client hooks import `macaw_component`'s shared client module (the
announcer and the client bus, chapter 6), serve that package's `priv/static` from your
endpoint as well, beside your own `Plug.Static`:
`plug Plug.Static, at: "/", from: {:macaw_component, "priv/static"}, only: ~w(macaw_component)`.
Hooks import it from `Macaw.Component.Client.module_url/0`, `/macaw_component/client.js`.
The same plug serves the drawn states' notices' stylesheet: link
`Macaw.Component.Drawn.stylesheet_url/0`, `/macaw_component/drawn.css`, with the others.

**Content Security Policy.** Nothing a surface renders is inline: no `style` attributes,
no `<style>` elements, no inline scripts, nothing from another origin. A policy of
`default-src 'self'` holds for every Macaw surface. (`macaw_plug`, a separate host
library, sets security headers; it isn't required.)

## Pitfalls

- **Building a registry per request.** Build it once, at boot, from your configuration
  (`MyApp.Boot.macaw!/0`), and pass it; a bad package fails there.
- **Validating per request.** `show/2` validates on every call: fine for a one-off, wasted
  on a page served per request. Validate when the document loads or changes, keep the
  validated surface, and call `Macaw.Surface.render/2` per request (chapter 4,
  "Rendering").
- **No registry.** Without `registry:`, `show/2` validates against the built-in registry
  alone, so a document naming one of your components answers `:unknown_component`.
- **No ceiling.** `show/2` answers `{:error, [{[:ceiling], :required}]}` without
  `ceiling:`: choose the most rows a slot may receive, once, in your configuration.
- **Credentials in documents.** Documents name sources; `sources/0` is where names become
  configured structs. Keep secrets in your app's configuration.
- **Validating with a viewer.** Validation never sees one; pass `viewer:` to `show/2`
  for fetching, and let sources filter by it.
- **Reading the clock yourself.** `show/2` reads it once per call; pass `now:` only in
  tests, or to render several surfaces at one instant.
- **Hand-written `<style>` for surfaces.** Serve the layout, table and theme stylesheets,
  and style Macaw's other classes in your app's CSS. A surface on an areas layout has its
  template's own sheet: list it from `Macaw.Surface.stylesheet/1`.
- **Relying on the table's sort buttons without handling `"mw-event"`.** A click reaches
  your LiveView and nothing else: apply it with `Macaw.State` (chapter 4), or render with
  `links:` so a click is a visit.

## Recap

- `config :my_app, :macaw` holds the packages and the ceiling; `Macaw.Registry.from_config!/1`
  builds the registry from it at boot, and every `show/2` is passed it and the ceiling.
- One module of your app holds the source map and the documents, and shows them with
  `Macaw.Surface.show/2`.
- A surface's HTML is a safe value: output it in any HEEx template.
- In a LiveView, pass `socket:`: `:socketless` until connected, then `:live`.
- A component's events reach `handle_event("mw-event", ...)`: `Macaw.State.event/3`
  reads one, `apply/2` applies it, and `persist/3` and `restore/3` keep the state.
- Serve the layout's (`Macaw.Surface.stylesheet/1`), the table's and the theme
  stylesheets at their content addresses; no inline styles.

**Further reading:** goals 2 to 5 in [spec/00 §2](https://github.com/dcoai/macaw/blob/main/spec/00-overview.md#overview-goals), and the strict delivery rules in [spec/10 §1](https://github.com/dcoai/macaw/blob/main/spec/10-web.md#web-csp).

Next: [chapter 11, Operations and derived sources](11-operations-and-derived.md).
