# `Macaw.Live`
[🔗](https://github.com/dcoai/macaw_live/blob/v0.1.0/lib/macaw/live.ex#L1)

Macaw's LiveView runtime (spec/00): a runtime around Macaw's pure values, never a second
state model. `Macaw.State` stays the state, `Macaw.Surface.fetch/2` and `render/3` stay
the fetch and the render, and a contained component stays a pure value with transitions;
`macaw_live` decides only where these run and how changes travel (spec/00 §1).

A host adds one `Macaw.Live.Supervisor` to its tree and **mounts a surface with one call**
in its LiveView's `mount/3` (spec/01 §2), writing no `handle_event/3` and no
`handle_info/2` for it:

    def mount(_params, _session, socket) do
      Macaw.Live.mount(socket, surface,
        live: MyApp.Macaw,
        sources: %{"services" => {%MyApp.Services{}, nil}},
        registry: MyApp.registry(),
        ceiling: 5_000
      )
    end

**The wire is encoded with OTP's `:json`** (spec/07 §10): a host configures Elixir's
`JSON`, which has the three functions Phoenix asks of its JSON library, as Phoenix's
JSON library, where Jason costs about four times the reductions on every viewer's every
diff. `info/1` reports the library in use.

    # config/config.exs
    config :phoenix, :json_library, JSON

**A page holds no rows** (spec/03 §2.2): its readers' rows are their source managers'
tables', so an idle page's process is its state and its reads. LiveView hibernates a page
idle for its endpoint's `hibernate_after` (15,000 ms by default), which compacts its
heap; a host keeping many idle pages may lower it:

    # config/config.exs
    config :my_app, MyAppWeb.Endpoint, live_view: [hibernate_after: 5_000]

**A live table's scroll is its state** (spec/05 §10): the surface's hook moves a live
table's range with the table's own `range` event, which sets its `<cell>.first` state as
its sort sets `sort`. A host persisting that state persists the scroll position with it:
persisted in the URL (`Macaw.State.Persistence.Url`), the address carries the first row
shown, so a reload or a shared link opens the table where it was. That is the host's
choice, made with its persistence's names.

This module also carries the host's calls on a mounted surface (spec/01 §6). Each takes
a socket the runtime mounted; one it didn't is a wrong call.

# `announce`

```elixir
@spec announce(Phoenix.LiveView.Socket.t(), String.t(), keyword() | map()) ::
  {:ok, Phoenix.LiveView.Socket.t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

Asks the page's announcer to speak for a mounted instance (spec/05 §4): the request is
built by `Macaw.Component.Announcement.new/2` against the instance's declarations and
pushed as `"mw:announce"`. `Macaw.Live.Client.announce/3`, whose faults it answers.

# `apply`

```elixir
@spec apply(Phoenix.LiveView.Socket.t(), String.t(), term()) ::
  {:ok, Phoenix.LiveView.Socket.t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

A host's or the system's `%Macaw.Data.Event{}` (initiator `:system`) applied to a mounted
surface by the event path from its step 3 (spec/01 §5, §6): applied, persisted, and only
what it affects rendered. `{:ok, socket}`, or `{:error, faults}` with nothing changed:
`{[:surface], {:not_mounted, name}}` for a name not mounted, `{[:event], {:type, :event}}`
for what isn't an event, and the state's faults.

# `focus`

```elixir
@spec focus(Phoenix.LiveView.Socket.t(), String.t()) ::
  {:ok, Phoenix.LiveView.Socket.t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

Moves the viewer's focus to the element of an id (spec/05 §5), pushed as `"mw:focus"`.
`Macaw.Live.Client.focus/2`, whose faults it answers.

# `info`

```elixir
@spec info(Phoenix.LiveView.Socket.t()) :: map()
```

The runtime's present state (spec/01 §6): per surface its state values, whether it is
shown (a closed pane isn't, spec/01 §8), its last navigation step's faults (spec/01 §9),
its last theme relink's faults (`theme`, spec/06 §2.4),
and per cell its drawn state, crash reason, process, restarts and last sequence; the
readers' statuses by source and reader (`sources`); the turns' state; the edges'
sequences, and the values a mirror dropped (spec/04 §1); `budget`, the visit's event
budget as the page holds it, `:unlimited` or its rate, burst, the events it dropped,
whether the last was dropped and the last one's fault (spec/01 §5.1); and `json_library`, the module Phoenix encodes the wire
with (`Phoenix.json_library/0`), `JSON` as spec/07 §10 recommends.

# `mount`

```elixir
@spec mount(Phoenix.LiveView.Socket.t(), surface, keyword()) ::
  {:ok, Phoenix.LiveView.Socket.t()} | {:error, [Macaw.Base.Fault.t(), ...]}
when surface:
       Macaw.Surface.t()
       | {:ok, Macaw.Surface.t()}
       | {:error, list()}
       | keyword()
       | map()
```

Mounts a surface in a LiveView (spec/01 §2): `{:ok, socket}` with `socket.assigns.macaw`
the `%Macaw.Live.Mounted{}` and the runtime's `%Macaw.Live.Page{}` in the socket's
private data, or `{:error, faults}` with nothing started, attached or assigned.

`surface` is what `Macaw.Surface.show/2` takes: a surface, a pipe from `new/1` or
`build/2`, or attrs. `env` is `show/2`'s, less `now:` and `mode:` (the clock and the
socket decide them), plus the runtime's keys: `live:` (required, the supervisor's name),
`host:`, `persistence:`, `clock:`, `debounce:`, `tick:`, `stale_after:`, `first_wait:`,
`max_heap:`, `cell_timeout:`, `render_timeout:`, `render_reductions:`, `navigation:`,
`shared_key:`, `page:` and `viewer_id:` (the instances of the `:page` and `:viewer`
scopes), `session_persistence:` and `viewer_persistence:` (each `[module: module,
carrier: carrier]`, the host's persistence of `:session` and `:viewer` state, spec/04
§5), and `derived:`, a `Macaw.Data.Derived.Engine` whose sources, each by the
name of its one-element path, the surface binds as any other source and the page runs in
its pulses (spec/03 §3 stage 4), `event_budget:`, the visit's event budget
(`[per_second: 20, burst: 40]` unless given, or `:unlimited`; spec/01 §5.1,
`Macaw.Live.Visit.Budget`), and `overlays:`, the host's policy for each source the
surface's `add` and `remove` actions change (`Macaw.State.new/2`'s, macaw spec/13 §3.1;
`%{}` unless given): its row rules, whether this viewer may write, where the changes
are held (`:visit` or `:session`), its params' filters and its cap. The visit holds the
changes (spec/01 §5.4, spec/04 §5); a URL never carries them.

What it does, in order: reads `env`; builds and validates the surface against the
registry and sources; builds the state (`state:`, else `Macaw.State.new/2` with `host:`,
`overlays:` and `instances:`); puts its `:viewer` values from the host's carrier, its `:session`
values from its transport's `Macaw.Live.Visit` (or the carrier, before the socket
connects) and, connected, its `:page` values the page's (spec/04 §5);
fetches once with `Macaw.Surface.fetch/2` at the clock's now and builds each cell; attaches
its hooks, once per socket however many surfaces it mounts (`:handle_event`,
`:handle_info`, and `:handle_params` when a surface's persistence is `Url`), each halting
on what is the runtime's and continuing on everything else.

Its faults, every one at once, in this order: `show/2`'s for the first argument and the
`env` keys it shares, as `show/2` words them; the runtime's keys (`{[:live], :required}`,
`{[:live], {:not_running, name}}`, `{[key], {:type, :pos_integer}}`, `{[:debounce], {:type,
:non_neg_integer}}`, `{[:clock], {:type, :clock}}`, `{[:navigation], {:type,
:navigation}}`, `{[:persistence, :module], {:type, :persistence}}`, `{[:persistence, :to],
:not_a_function}`, `{[:host], {:type, :map}}`, `{[:derived], {:type, :engine}}`, `{[:event_budget], {:type,
:event_budget}}`, `{[:event_budget, key], :unknown_key}`, `{[:event_budget, key], {:type,
:pos_integer}}`, and
`{[:persistence, :module], :not_routed}`
for `Url` persistence in a LiveView not mounted at the router, where no `handle_params`
runs); validation's, unchanged; then
`Macaw.State.new/2`'s; then `{[:surface], {:mounted, name}}` for a name this socket
already mounts; then the asset store's, `{[:assets], {:store, reason}}`, or a hand-built
theme's name, `{[:theme, :name], {:type, :word}}` (every stylesheet of the surface's
layout, theme and cells is registered before its first render, spec/06 §2.1); then
`{[:shortcuts, key], {:duplicate_shortcut, key, [id, id]}}` for a key two shortcuts
share across the page's mounted cells (spec/05 §6). It never raises on a document, a
source map or an env value.

# `mount!`

```elixir
@spec mount!(Phoenix.LiveView.Socket.t(), term(), keyword()) ::
  Phoenix.LiveView.Socket.t()
```

`mount/3`, raising its faults as an `ArgumentError` for a host at boot: the socket, or
the raise.

# `mount_page`

```elixir
@spec mount_page(Phoenix.LiveView.Socket.t(), term(), term()) ::
  {:ok, Phoenix.LiveView.Socket.t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

Mounts a page (spec/01 §8): `{:ok, socket}`, or `{:error, faults}` with nothing kept.
`page` is a `%Macaw.Page{}`; `env` is `mount/3`'s, plus `surfaces:` (required, the
surfaces its regions may name, by name) and `pages:` (the pages its `navigate` actions
may name, `%{}` by default), the host's pages as `validate_pages/1` validated them once,
at boot or load. The page's path is the `:page` instance unless `page:` gives one.

What it does, in order: judges `env` as `mount/3` does; validates the page with
`Macaw.Page.validate/3`, which builds its DAG across every process the runtime will
place its nodes in and refuses a cycle, a cycle through a persistent region among them,
naming it (`{:cycle, nodes}`, macaw spec/03 §6.2); connected, registers the page by its
transport in the supervisor's `Registry` (spec/04 §3); mounts every surface of each
region that isn't persistent in this process, panes among them, in page order
(`Macaw.Page.surfaces/1`), by `mount/3`'s steps, a pane its container doesn't show
mounted closed: its state held and its exports published, no cell built until it opens
(spec/01 §8); then, connected, puts each export its own mirrors read into them, opens its
exports edge to the persistent regions' mirrors, joins the exports of each persistent
region it reads, and tells each persistent region of the transport that it is there.

A persistent region is a `Macaw.Live.Region` of its own process, which the page's
template renders with `Macaw.Live.Region.live_render/2`; it asks the page for its content
and joins its edges (spec/04 §3). Only exports cross processes (spec/04 §6). A pane
reaches the template through its container's cell, never as a surface of `@macaw`. Each
`navigate` step a cell's event takes goes to the `navigation:` behavior after the
event's renders (spec/01 §9, `Macaw.Live.Navigation`).

Its faults, every one at once: `{[], {:type, :keyword}}` for an `env` that isn't a keyword
list, `{[:page], {:type, :page}}` for a page that isn't one; `mount/3`'s for the env, with
`{[:pages], {:type, :map}}` for `pages:` that aren't a map and `{[:pages, name], {:type,
:validated_page}}` for one that isn't `validate_pages/1`'s under its own name; then
`Macaw.Page.validate/3`'s; then `{[:page], :mounted}` for a socket that mounts a page
already; then each surface's `mount/3` faults at `[:regions, region, i | path]`.

# `notify`

```elixir
@spec notify(atom(), String.t(), Macaw.Data.Source.Change.what()) ::
  :ok | {:error, [Macaw.Base.Fault.t(), ...]}
```

Announces that a source's data changed (spec/03 §7), by the name the host maps it under
in its `sources:`, the one name a writer and a page share: every source manager of the
supervisor `live` of that name reads again what `what` names, once for a burst, and
tells the pages whose windows the read changes.

    :ok = Macaw.Live.notify(MyApp.Macaw, "services")
    :ok = Macaw.Live.notify(MyApp.Macaw, "readings", {:range, from, to})
    :ok = Macaw.Live.notify(MyApp.Macaw, "services", {:identities, [42]})

`what` is a change notice's (macaw_data's `Macaw.Data.Source.Change`): `{:range, from,
to}`, the window field's values from `from` up to but not including `to`, either `nil`
for open; `{:identities, ids}`, the rows of those identities wherever they lie; or
`:all`, everything held (the default).

`:ok`, or `{:error, faults}`, every fault at once: `{[:live], {:not_running, live}}`,
`{[:name], {:type, :string}}`, `Change.new/2`'s faults of `what` (`{[:what], ...}`), or
`{[:notify], {:broadcast, reason}}` for a transport that answered an error.

# `put_sources`

```elixir
@spec put_sources(Phoenix.LiveView.Socket.t(), String.t(), term()) ::
  {:ok, Phoenix.LiveView.Socket.t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

The mounted surface's sources replaced (spec/01 §6): its readers rebuilt, and only the
cells reading a source whose entry changed fetched again, a slot whose source is gone or
malformed drawn `invalid` as `Macaw.Surface.fetch/2` draws it. `{:ok, socket}`, or
`{:error, faults}`: `{[:surface], {:not_mounted, name}}`, `{[:sources], {:type, :map}}`.

# `shortcuts`

```elixir
@spec shortcuts(map()) :: Phoenix.LiveView.Rendered.t()
```

The page's shortcuts dialog (spec/05 §6), `Macaw.Live.Shortcuts.dialog/1`, placed once
by the host: attribute `macaw` (the `%Macaw.Live.Mounted{}`), required.

    <Macaw.Live.shortcuts macaw={@macaw} />

# `state`

```elixir
@spec state(Phoenix.LiveView.Socket.t(), String.t()) ::
  {:ok, Macaw.State.t()} | :error
```

The mounted surface's state (spec/01 §6): `{:ok, %Macaw.State{}}`, or `:error` for a name
not mounted.

# `stylesheets`

```elixir
@spec stylesheets(map()) :: Phoenix.LiveView.Rendered.t()
```

The page's stylesheet links (spec/06 §2.3), `Macaw.Live.Assets.links/1`, placed once by
the host in its layout: attribute `macaw` (the `%Macaw.Live.Mounted{}`), required.

    <Macaw.Live.stylesheets macaw={@macaw} />

# `surface`

```elixir
@spec surface(map()) :: Phoenix.LiveView.Rendered.t()
```

The function component a template renders a mounted surface with (spec/01 §3.1),
`Macaw.Live.Surface.render/1`: attributes `macaw` (the `%Macaw.Live.Mounted{}`) and
`name` (a mounted surface's name), both required.

    <Macaw.Live.surface macaw={@macaw} name="status" />

# `unmount`

```elixir
@spec unmount(Phoenix.LiveView.Socket.t(), String.t()) ::
  {:ok, Phoenix.LiveView.Socket.t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

A mounted surface unmounted (spec/01 §6): its cells stopped, its readers removed, its
edges left and its entry removed from `%Macaw.Live.Mounted{}`. `{:ok, socket}`, or
`{:error, [{[:surface], {:not_mounted, name}}]}`; every other surface runs on.

# `validate_pages`

```elixir
@spec validate_pages(term()) ::
  {:ok, %{required(String.t()) =&gt; Macaw.Page.Validated.t()}}
  | {:error, [Macaw.Base.Fault.t(), ...]}
```

The host's pages validated once (spec/01 §9), at boot or when they load, for
`mount_page/3`'s `pages:`: `{:ok, %{name => %Macaw.Page.Validated{}}}`, or `{:error,
faults}`, every page's at once. A host holds the answer and passes it to each mount, so
no navigation validates a page again (`Macaw.Live.Navigation.follow/3`), and nothing of
it is global.

`env` holds `pages:` (required, a map of name to `%Macaw.Page{}`, each under its own
name), `surfaces:` (required, the surfaces their regions may name, by name), `sources:`
(required) and `registry:` (the built-in registry unless given), as `mount_page/3` takes
them. Each page is validated with `Macaw.Page.validate/3` against the others as its
`navigate` targets, as macaw spec/07 §2 validates a document when it loads.

Its faults: `{[], {:type, :keyword}}` for an `env` that isn't a keyword list; `{[key],
:required}` and `{[key], {:type, :map}}` for `pages:`, `surfaces:` and `sources:`;
`{[:registry], {:type, :registry}}`; `{[key], :unknown_key}` for any other key; then each
page's validation faults at `[:pages, name | path]`.

---

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