# `Macaw.Surface`
[🔗](https://github.com/dcoai/macaw/blob/v0.6.0/lib/macaw/surface.ex#L1)

A surface: a reusable composed unit of cells, laid out by its layout (spec/06 §3.1,
§3.3), the 12-column grid by default.

    {:ok, surface} =
      Macaw.Surface.new(
        name: "service_overview",
        title: "Service overview",
        cells: %{
          "latency" => %{component: "macaw.table", place: %{x: 0, y: 0, w: 6, h: 4},
                         slots: %{"rows" => %{source: "latency"}}}
        }
      )

A surface is a document whose value is a term, read from JSON through the kernel's gates
and stacked as a fragment:

  * its value is `%{version: v, surface: node}` (`to_map/1`), judged as terms by
    `from_map/1`; its settings and params are the terms they are, checked against the
    component's and the sources' parameter types by `validate/3`;
  * the JSON form, `{"$version": v, "surface": {…}}`, is an adapter at the edge:
    `to_json/1` writes it, refusing at its path a value JSON can't hold, and `from_json/2`
    reads it back through every gate (the version, the limits, the migration), then
    `new/1`;
  * as a fragment type, `cells`, `state` and `links` are each a `:union` by name and
    every other key an `:override`, so a layer adds or replaces cells, state sources and
    links by name and overrides the title.

A surface may declare state sources (`state:`, each a `Macaw.State.Source`), and its
cells bind settings, request params and slots to them (`{:state, name}`) and set them
from their components' events (`actions:`) (spec/03 §1.1, §1.3, §1.4). Its `variables:`
are parameters, each held as a state source of its name (spec/03 §1.7.2). Its `links:` say
which differently named identity fields are one identity, each field to its canonical
name, so a `selection` written in one source's field is read in another's (spec/03 §7).
Its `exports:` name the state it makes public, each a path to state, and a cell's
`exports:` its own; another surface reads one only through a mirror, a state source
declaring `from: {:export, surface, name}` (spec/03 §5). A surface with no state and no links is the value, and writes the document, it always
did.

Names are strings, an atom read as its spelling; no atom is made from a document.

# `cell_spec`

```elixir
@type cell_spec() :: %{
  name: String.t(),
  module: module(),
  kind: atom(),
  classes: String.t(),
  instance: String.t(),
  assigns: map()
}
```

One cell as `cells/3` gives it: what its component renders, and where.

# `chrome`

```elixir
@type chrome() :: %{open: Phoenix.HTML.safe(), close: Phoenix.HTML.safe()}
```

The surface's markup around its cells, as `chrome/2` gives it.

# `reader`

```elixir
@type reader() ::
  {:source, String.t(), Macaw.Data.Source.Request.t()}
  | {:derived, String.t(), Macaw.Data.Source.Request.t()}
  | {:state, String.t()}
  | {:invalid, [Macaw.Base.Fault.t(), ...]}
```

A slot's reader (`readers/2`): what fetching asks for it, or why it asks nothing.

# `reader_entry`

```elixir
@type reader_entry() :: %{
  cell: String.t(),
  slot: String.t(),
  reader: reader(),
  clamped: boolean()
}
```

One slot's reader in `readers/2`'s answer, with its cell and slot.

# `reader_status`

```elixir
@type reader_status() ::
  :live
  | :loading
  | :stale
  | {:down, term()}
  | {:invalid, [Macaw.Base.Fault.t()]}
```

A reader's status, as `drawn/2` reads it.

# `t`

```elixir
@type t() :: %Macaw.Surface{
  cells: %{required(String.t()) =&gt; Macaw.Surface.Cell.t()},
  colors: %{required(String.t()) =&gt; %{required(String.t()) =&gt; term()}},
  exports: %{required(String.t()) =&gt; String.t()},
  layout: Macaw.Layout.spec(),
  links: %{required(String.t()) =&gt; String.t()},
  name: String.t(),
  state: %{required(String.t()) =&gt; Macaw.State.Source.t()},
  title: String.t() | nil,
  variables: term()
}
```

# `build`

```elixir
@spec build(String.t() | atom(), keyword()) ::
  {:ok, t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

A surface in its short code form (spec/06 §3.8): its name, then its keys, each cell
`{component, opts}` with `opts` the rest of the cell's keys, in a list, so the cells
take their order and their names from it. It is `new/1` of the same keys, and the
surface it answers is equal to the one written out.

    iex> {:ok, short} = Macaw.Surface.build("status", cells: [{"macaw.table", source: "services"}])
    iex> Macaw.Surface.new(
    ...>   name: "status",
    ...>   layout: {:stack, order: ["table_services"]},
    ...>   cells: %{"table_services" => %{component: "macaw.table", source: "services"}}
    ...> ) == {:ok, short}
    true

# `build!`

```elixir
@spec build!(String.t() | atom(), keyword()) :: t()
```

`build/2`, or an `ArgumentError` naming every fault: a surface written in code.

# `cell`

```elixir
@spec cell(Macaw.Surface.Validated.t(), String.t(), map(), keyword()) ::
  {:ok, cell_spec()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

One cell as `cells/3` builds it (spec/06 §3.6): `{:ok, cell}`, the entry of `cells/3`
named `name`, at the cost of that cell alone, whatever the surface's other cells, so a
runtime re-renders one cell without building the rest. `fetched` and `env` are as for
`cells/3`, and only `name`'s entry of `fetched` is read. It is `cells/4` of one name.

Its faults are `cells/3`'s, and a name no cell of the surface has,
`{[:name], {:unknown_cell, name}}`, never a raise.

# `cells`

```elixir
@spec cells(Macaw.Surface.Validated.t(), map(), keyword()) ::
  {:ok, [cell_spec()]} | {:error, [Macaw.Base.Fault.t(), ...]}
```

Each cell as `render/3` renders it (spec/06 §3.6), in reading order: `{:ok, cells}`, or
`{:error, faults}` for an `env` or `fetched` it can't render, never a raise. `fetched` is
`fetch/2`'s answer and `env` is `render/3`'s, with `values:`, a map of cell name to a
`:contained` cell's value: given, it is the cell's value as it is, and otherwise its
value is built by its transitions (`init/2`, each delivery in slot order, each bound
setting through `bound/3` in name order, then `size/2`). Each cell is `%{name:, module:,
kind:, classes:, instance:, assigns:}`: its component renders `module.render(kind,
assigns)` with the seven assigns (its context, settings, declarations, drawn state,
deliveries or value, and what its component prepared for the placement) inside `<div
class="classes" id="instance">`.

Its faults: `{[:now], :required}`, a value a cell's context refuses by its key (`[:now]`,
`[:width]`, `[:row_height]`, `[:mode]`, `[:theme]`, `[:heading_level]`, `[:links]`),
`{[:values], {:type, :map}}`, `{[key], :duplicate}` for a key given twice, a state it
can't render at (`{[:state], …}` or
`Macaw.State.new/2`'s), and a cell `fetched` lacks or holds in no shape, at `[:fetched,
name]`; an `env` that isn't a keyword list is `{[], {:type, :keyword}}`.

# `cells`

```elixir
@spec cells(Macaw.Surface.Validated.t(), [String.t()], map(), keyword()) ::
  {:ok, [cell_spec()]} | {:error, [Macaw.Base.Fault.t(), ...]}
```

The cells named, as `cells/3` builds them (spec/06 §3.6): `{:ok, cells}`, `cells/3`'s
entry of each name, in the order named. What every cell is built from (the env judged,
the state resolved, the link builder, the cells' heading level) is built once for all of
them, so a runtime re-rendering the k cells an event affects pays for it once, not k
times. `fetched` and `env` are as for `cells/3`, and only the named cells' entries of
`fetched` are read. `cells/3` is it over the reading order, and `cell/4` over one name.

Its faults are `cells/3`'s, then `{[:names], {:unknown_cell, name}}` for each name no
cell of the surface has, and `{[:names], {:type, :list}}` for names that aren't a list,
never a raise.

# `chrome`

```elixir
@spec chrome(Macaw.Surface.Validated.t(), keyword()) ::
  {:ok, chrome()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

The surface's markup around its cells (spec/06 §3.6): `{:ok, %{open:, close:}}`, two
safe values, the surface's `div`, its title at `heading_level:` (`2`) and its layout's
container, then their closing tags. `render/3` is `open`, each of `cells/3`'s cells in
its `div`, then `close`. A `heading_level:` that isn't one is its fault, and so is a key
given twice, `{[key], :duplicate}`; an `env` that
isn't a keyword list is `{[], {:type, :keyword}}`.

# `drawn`

```elixir
@spec drawn(reader_status(), Macaw.Data.Delivery.t() | nil) ::
  {:ok, Macaw.Component.Drawn.t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

A slot's drawn state from its reader's status and its delivery (spec/06 §3.5), the rule
`fetch/2` draws by: `{:ok, state}`, or `{:error, faults}` for a status or delivery it
doesn't know. `delivery` is the slot's delivery, the last one kept, or `nil`; `status`:

  * `:live`, answered: the delivery's facts in the one precedence, `no_data` for an
    empty one (or none) whatever else it says, `stale` for `served.stale` (also when
    capped), `capped` for `capped` or `reduced_by` anything, else `live`;
  * `:stale`, unanswered past its time: `stale`, unless the delivery is empty;
  * `:loading` is `loading`; `{:down, reason}` is `down`, but a derived source down with
    a last good output (`{:down, {:derived, id, kind}}` and a delivery) is `stale`;
  * `{:invalid, faults}` is `invalid`.

A cell's state is its slots' highest, `Macaw.Component.Drawn.pick/1`.

# `expand`

```elixir
@spec expand(t(), Macaw.Registry.t()) :: t()
```

The surface with its cells' default actions written out (spec/03 §1.3): each per-cell
state declared under its name, `<cell>.<param>`, each parameter bound to it, and each
cell's actions listed in full, its own and then the defaults', so nothing is hidden and
an author can see or copy the wiring.

It validates to the same cells and state as the surface given, and expanding again
changes nothing. A cell whose component the registry lacks, or whose declarations or
defaults fail, is left as written, for `validate/3` to report.

    iex> registry = Macaw.Registry.new!([Macaw.Builtin])
    iex> short = Macaw.Surface.build!("status", cells: [{"macaw.table", source: "services"}])
    iex> expanded = Macaw.Surface.expand(short, registry)
    iex> expanded.cells["table_services"].settings
    %{"first" => {:state, "table_services.first"}, "order" => {:state, "table_services.order"}, "sort" => {:state, "table_services.sort"}}
    iex> Map.keys(expanded.state)
    ["table_services.first", "table_services.order", "table_services.sort"]
    iex> Macaw.Surface.expand(expanded, registry) == expanded
    true

# `explain_settings`

```elixir
@spec explain_settings(Macaw.Surface.Validated.t(), String.t()) ::
  {:ok, [map()]} | :error
```

Which layer set each of a cell's settings (spec/07 §1): `{:ok, entries}`, or `:error` for
a name that is no cell of the surface. A configured component is one stack, its
component's defaults, then its preset when it names one, then its own settings, and each
entry is `%{path: [param], value, layer, overrode}`, in name order: `layer` is
`:defaults`, `{:preset, name}` or `:cell`, and `overrode` the layers below it that held
the setting, lowest first (`Macaw.Preset.explain/1`). So "why is this table sorted by
date?" is answered like any other value. The layers are built here, when asked, never
when the surface is validated, so a host that never explains pays nothing for them.

    iex> surface = Macaw.Surface.build!("status", cells: [{"macaw.table", name: "services", source: "services", settings: %{"order" => "desc"}}])
    iex> sources = %{"services" => {%Macaw.Test.Rows{}, nil}}
    iex> {:ok, validated} = Macaw.Surface.validate(surface, Macaw.Registry.new!([Macaw.Builtin]), sources)
    iex> {:ok, entries} = Macaw.Surface.explain_settings(validated, "services")
    iex> Enum.find(entries, &(&1.path == ["order"]))
    %{path: ["order"], value: "desc", layer: :cell, overrode: [:defaults]}

# `fetch`

```elixir
@spec fetch(Macaw.Surface.Validated.t(), keyword()) :: %{
  required(String.t()) =&gt; map()
}
```

Each cell's deliveries and drawn state (spec/06 §3.5): `%{cell => %{deliveries:, drawn:}}`.
`env`: `sources:` (as given to `validate/3`), `now:` and `ceiling:` (required),
`viewer:` (`nil`), `width:` (`1200`), `row_height:` (`64`), `timeout:` (`5_000` ms), and
`state:`, a `%Macaw.State{}` of this surface (without it, every state source at its
initial value), and `mode:`, `theme:`, `heading_level:` and `links:` as `render/3` reads
them: each slot's budget is asked in the context its cell renders in, its size the
cell's declared size. Bound values are resolved first (spec/03 §1.4): each request param bound
to a state takes its value, a slot bound to a state is delivered from it, and a slot
whose source has a window field of the window's kind carries the `window` (a time
window over a `:time` field, a numeric range over a `:number` one, both as the request's
`window`, a box over a `:point` one as its `box`), all before pooling.
Each fetch runs bounded in a process of its own, so it never blocks or crashes the caller.
With `manager:`, a host's `Macaw.Surface.Reader` as `{module, arg}` (#443), each pooled
request is read through its `window/3` once, in the caller, instead of fetched from the
source, and what it answers is packed, finished and reduced as a fetch's is; its
`:loading` draws the cells `loading` and its error `down`. A source gone or malformed since validation draws its cell `invalid`, and so does a value
of `env` that can't fetch: a `ceiling:` that isn't a positive integer, a `now:` that isn't
a `DateTime`, a `width:` or `row_height:` that isn't a positive number, a `timeout:` that
isn't a non-negative integer, a `mode:`, `theme:`, `heading_level:` or `links:` a cell's
context refuses, a `manager:` that isn't `nil` or a reader (`{[:manager], {:type,
:reader}}`), any key given twice, a `state:` that isn't one of this surface, or no `state:`
for a surface whose initial values need the host's. A bound param the source refuses
draws its cell `invalid`. Leaving out `now:` or `ceiling:` is a wrong call, and raises.

# `fragment`

```elixir
@spec fragment(t()) :: %{surface: map()}
```

`%{surface: node}`: the surface as a fragment.

# `from_json`

```elixir
@spec from_json(String.t(), keyword()) ::
  {:ok, t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

The surface a JSON document holds: read through the JSON adapter
(`Macaw.Layers.Form.read/3`: every gate, the version, the limits and the migration, then
the value, judged, then every URL against the host's policy), then `new/1`, every fault
by path from the document as `from_map/2` gives them. `limits:` as
`Macaw.Layers.Form.gates/3` takes them; `vocabulary:` the atoms a setting or param may
spell beyond the document's own words, since no other atom is made from a document;
`urls:` the host's `Macaw.Layers.Url.Policy`, closed when not given (`from_map/2`).

# `from_map`

```elixir
@spec from_map(term(), keyword()) ::
  {:ok, t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

The surface a document value holds, judged as terms, or every fault by path from the
document: the version first, so nothing of a newer document is judged, then the
envelope, then every URL it holds against the host's policy, then `new/1` (its faults
under `:surface`). No form is written or read, so no limit applies: the limits bound
what reading an encoding costs (`from_json/2`).

`urls:` the `Macaw.Layers.Url.Policy` the host reads with, as `from_json/2` takes it:
without it, the empty policy, which allows no URL. A URL it refuses is
`{path, {:url, reason}}`, never quoting the URL, at the path `from_json/2` gives, so the
two readers answer one document alike (spec/06 §3.1). A `urls:` that isn't a policy is
`{:type, :url_policy}` at `[:urls]`, judged before the document.

# `legal`

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

The current legal values of every state source declaring `values_from` (spec/07 §2.2):
`{:ok, legal}`, each such state's values by name, a `MapSet` of them, a category's by
spelling, for `Macaw.State.apply/3`'s `legal:`, or every fault at once. Each value is
spelled once here, so checking an event's write is a membership test of each value it
writes, whatever the number of legal ones. This is the request-time check's I/O: each `"source.field"` is
read once through the host's source, with the request's viewer: the field's declared
values when its schema has them, else the distinct values of a fetch of it, bounded as a
slot's fetch is, or, with `manager:`, its distinct values read through the host's
`Macaw.Surface.Reader` (`distinct/4`, #443). It is `legal/3` with every name; a host
checking one event reads only the states it writes with `legal/3`'s `names:`.

`env`: `sources:`, the host's sources by name, and `now:`, required; `viewer:`, `nil`
for the anonymous viewer; `timeout:`, 5 seconds; `manager:`, `nil` or a reader as
`{module, arg}`. A bad env is its faults by key (`{[:sources], {:type, :map}}`,
`{[:now], :required}`, `{[:manager], {:type, :reader}}`, `{[key], :unknown_key}` and the
like). A state whose values can't be read is a fault at `[:state, name, :values_from]`:
`{:unknown_source, name}`, `{:bad_source, name}`, `{:unknown_field, field}`, or
`{:unavailable, why}` for a source that can't answer now.

    iex> rows = [%{"t" => ~U[2026-11-18 12:00:00Z], "v" => 1, "host" => "a"}, %{"t" => ~U[2026-11-18 12:01:00Z], "v" => 2, "host" => "b"}]
    iex> sources = %{"services" => {%Macaw.Test.Rows{rows: rows}, nil}}
    iex> surface = Macaw.Surface.build!("status", state: %{"host" => %{type: :category, values_from: "services.host"}}, cells: [{"macaw.table", source: "services"}])
    iex> {:ok, validated} = Macaw.Surface.validate(surface, Macaw.Registry.new!([Macaw.Builtin]), sources)
    iex> Macaw.Surface.legal(validated, sources: sources, now: ~U[2026-11-18 12:05:00Z])
    {:ok, %{"host" => MapSet.new(["a", "b"])}}

# `legal`

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

The current legal values of the named states only (spec/07 §2.2): `legal/2`'s answer
for those names, read at the cost of their sources alone, so a host checking one event
reads only the states its actions write (`Macaw.State.writes/2`), whatever the
surface's other states. `legal/2` is it with every name.

`options`: `names:`, the state names to read, every state's when not given. Each named
state declaring `values_from` answers its `MapSet` as `legal/2` does, its source and
field read once whatever the names that share them; a named state that doesn't declare
`values_from` answers no entry, and no source is read for it, a standard state or a
preference (spec/03 §1.2, §1.7.3) among them, since an action may write one. `env` is
`legal/2`'s, and its faults come with the options' at once: a name no state of the
surface has, `{[:names], {:unknown_state, name}}`; names that aren't a list,
`{[:names], {:type, :list}}`; another key, `{[key], :unknown_key}`; a key given twice,
`{[key], :duplicate}`; options that aren't a keyword list, `{[], {:type, :keyword}}`.

    iex> rows = [%{"t" => ~U[2026-11-18 12:00:00Z], "v" => 1, "host" => "a"}]
    iex> sources = %{"services" => {%Macaw.Test.Rows{rows: rows}, nil}}
    iex> state = %{"host" => %{type: :category, values_from: "services.host"}, "tier" => %{type: :category, values_from: "services.host"}, "open" => %{type: :number}}
    iex> surface = Macaw.Surface.build!("status", state: state, cells: [{"macaw.table", source: "services"}])
    iex> {:ok, validated} = Macaw.Surface.validate(surface, Macaw.Registry.new!([Macaw.Builtin]), sources)
    iex> env = [sources: sources, now: ~U[2026-11-18 12:05:00Z]]
    iex> Macaw.Surface.legal(validated, env, names: ["host", "open"])
    {:ok, %{"host" => MapSet.new(["a"])}}
    iex> Macaw.Surface.legal(validated, env, names: ["nope"])
    {:error, [{[:names], {:unknown_state, "nope"}}]}

# `new`

```elixir
@spec new(keyword() | map()) :: {:ok, t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

A surface from a keyword list or a map with atom keys: `{:ok, surface}` or every fault
at once, by path from the surface, in the kernel's order.

# `node`

```elixir
@spec node(t()) :: map()
```

The surface as its node: its keys, each cell as its map, every name a string and every
setting and param the term it is.

# `readers`

```elixir
@spec readers(Macaw.Surface.Validated.t(), keyword()) ::
  {:ok, [reader_entry()]} | {:error, [Macaw.Base.Fault.t(), ...]}
```

Each slot's reader as `fetch/2` builds it (spec/06 §3.5), pure: `{:ok, readers}` in
reading order (each cell in the surface's order, its slots by name), or `{:error,
faults}` for an `env` `fetch/2` refuses. `env` is `fetch/2`'s; `timeout:` is judged and
otherwise unread. Each reader is `%{cell:, slot:, reader:, clamped:}`, its `reader` one of:

  * `{:source, name, request}`: the host source `name`, asked `request`, a
    `Macaw.Data.Source.Request` with its params (bound values resolved), window, box
    and `as_of`, order (resolved through the slot's binding), budget (in the cell's
    context, at its declared size, clamped to the ceiling), viewer and now;
  * `{:derived, name, request}`: the same, of a source whose entry is a derived source's
    output (`Macaw.Data.Derived.Output`);
  * `{:state, name}`: a slot bound to the state source `name`, delivered from the state
    and never fetched;
  * `{:invalid, faults}`: a reader `fetch/2` draws `invalid`, by path from the surface:
    a bad budget, an order of no shape or naming a field the schema lacks, a bound param
    the source refuses, a source gone or malformed, or a request they can't make.

`clamped` is whether the ceiling cut the budget, so the delivery says `reduced_by:
:runtime`. `fetch/2` pools the source readers whose requests are equal but for their
budgets, at the largest. The faults of an `env` are by key: `{[:ceiling], :required}`,
`{[:now], :required}`, `fetch/2`'s bad values (a context's at `[:mode]`, `[:theme]`,
`[:heading_level]` and `[:links]` among them), and the state's
(`{[:state], {:type, :state}}`, `{:surface_mismatch, name}`, or `Macaw.State.new/2`'s);
an `env` that isn't a keyword list is `{[], {:type, :keyword}}`.

# `render`

```elixir
@spec render(Macaw.Surface.Validated.t(), keyword()) :: Phoenix.HTML.safe()
```

Fetches and renders in one call: `render(validated, fetch(validated, env), env)`, the env
judged once for both, and, when it gives no `legal:`, the view controls' legal values read
with its sources (spec/05 §6.7). Its keys are checked once for one given twice, its state
resolved and the viewer's preferences built once (spec/06 §3.6).

# `render`

```elixir
@spec render(Macaw.Surface.Validated.t(), map(), keyword()) :: Phoenix.HTML.safe()
```

The surface's markup (spec/06 §3.6), a safe value: its title at `heading_level:` (`2`),
then its cells in reading order, in `mode:` (`:socketless`), with `theme:`, `now:`,
`width:`, `row_height:` and `state:` as for fetching. Each setting bound to a state
renders at its value, through a `:contained` component's `bound/3`. With `links:`, the
host's `[params: params, to: fun]` (spec/03 §3.3), a `:socketless` render gives each cell
a link builder: an event's `href` is `to` of the params with the state the event would
give written in, so the table's sort headers are links to the sorted view. With `legal:`,
the current legal values by name as `Macaw.State.apply/3` takes them, the view controls
(spec/05 §6.7) offer them; a control a `values_from` state's values aren't given for draws
`loading`. It has no fault to
answer, so a value it can't build a cell's context from, or a state it can't render at,
is a wrong call, and raises (spec/00 §4.3).

# `show`

```elixir
@spec show(t() | {:ok, t()} | keyword() | map(), keyword()) ::
  {:ok, Phoenix.HTML.safe()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

A surface validated, fetched and rendered in one call (spec/06 §3.7): `{:ok, html}`, a
safe value, or `{:error, faults}`, validation's own. `surface` is a `%Macaw.Surface{}`,
`{:ok, surface}` or `{:error, faults}` (a pipe from `new/1` or `build/2`), or the attrs
`new/1` takes, whose faults are answered as they are.

`env` is as `fetch/2` and `render/3` take it, with defaults a host would otherwise
restate on every call:
- `sources:`, given once, required;
- `registry:`, the built-in registry (`Macaw.Registry.from_config([])`, a constant built
  when macaw is compiled, never per call) unless given, so
  a surface naming another package's component needs the host's registry;
- `now:`, one clock read here, in this host-side call, unless given (never in a source
  or a component);
- `ceiling:`, required: the most rows a slot may receive is the host's to choose, and a
  limit is never silently off;
- `mode:`, `:socketless` unless given, or, given a LiveView `socket:`, `:live` once it is
  connected and `:socketless` before, as `Phoenix.LiveView.connected?/1` reads it;
- `state:`, the surface's `%Macaw.State{}`, or every state source at its initial value
  when not given;
- `links:`, `nil` unless given, or the host's links for a render with no socket;
- `legal:`, the legal values the view controls offer (spec/05 §6.7), read here with
  `legal/3` of the controls' `values_from` states unless given.

It validates the surface on every call, so it is the convenience for a one-off. A hot
path validates once, when the document is loaded or changes, keeps the validated surface,
and calls `render/2` per request, or `fetch/2` once and `render/3` for each render of
that fetch with `values/3`'s answer as `values:`.

A surface that isn't one answers its own faults. An env that can't show it answers every
fault of the env, by its key: `{[:sources], :required}` (or `{:type, :map}`),
`{[:registry], {:type, :registry}}`, `{[:ceiling], :required}`, and a value given that
can't be used: `{[:ceiling], {:type, :pos_integer}}`, `{[:now], {:type, :time}}`, `{[:width],
{:type, :pos_number}}`, the same at `[:row_height]`, `{[:timeout], {:type,
:non_neg_integer}}`, `{[:manager], {:type, :reader}}`, and a context's faults at `[:mode]`, `[:theme]` and
`[:heading_level]`, a `links:` it can't use by key (`{[:links], {:type, :keyword}}`,
`{[:links, key], :unknown_key}`, `{[:links, :params], {:type, :map}}`, `{[:links, :to],
:required}`, `{[:links, :to], :not_a_function}`, and a `hidden:` that isn't a map of
text, `{[:links, :hidden], {:type, :map}}` or `{[:links, :hidden, name], {:type, :text}}`), a `legal:` `Macaw.State.apply/3`
refuses (`{[:legal], {:type, :map}}`), `{[:state], {:type, :state}}`, and
`{[key], :duplicate}` for any key given twice. An env that isn't a keyword list
is `{[], {:type, :keyword}}`. Then validation's faults; then a
state of another surface, `{[:state], {:surface_mismatch, name}}`, or, with no state,
`Macaw.State.new/2`'s faults.

# `stylesheet`

```elixir
@spec stylesheet(Macaw.Surface.Validated.t()) :: {String.t(), String.t()}
```

The stylesheet a validated surface's layout places its cells by, and its path, its content
address: `{path, css}`, for the host to serve from `'self'` (spec/06 §3.3). The grid's,
the stack's and the flow's are each one sheet; an areas layout's is its template's.

# `theme`

```elixir
@spec theme(Macaw.Surface.Validated.t(), keyword()) ::
  {:ok,
   %{
     theme: Macaw.Layers.Theme.t(),
     class: String.t() | nil,
     stylesheet: {String.t(), String.t()},
     faults: [Macaw.Base.Fault.t()]
   }}
  | {:error, [Macaw.Base.Fault.t(), ...]}
```

The theme a render of `env` applies (spec/06 §3.6, spec/03 §1.7.3): `{:ok, %{theme:,
class:, stylesheet:, faults:}}`. With the viewer's `theme` preference set to a name the
registry the surface was validated against holds (`Macaw.Registry.theme/2`), `theme` is
that theme, the one every cell's context carries whatever `theme:` the env gives, and
`class` its class, `"mw-theme-<name>"`, which the surface's `div` carries beside
`mw-surface`. Unset, `theme` is the env's `theme:`, else `Macaw.Layers.Theme.default/0`,
and `class` is `nil`: the render is what it always was. `stylesheet` is `{path, css}`, the
theme's rule (`Macaw.Layers.Theme.Sheet.rule/1`) at its content address, which the
host serves from `'self'` and the page links.

A preference naming no theme the registry holds is a fault, and the render falls back as
if it were unset: `faults` is `[{[:state, "theme"], {:unknown_theme, name}}]`, `[]`
otherwise. The state is `env`'s `state:` as the cells read it, so a live render of a new
state applies its theme, and so does one restored from a URL with no socket.

Its own faults, never a raise: a `theme:` a cell's context refuses, at `[:theme]`, any key
given twice, `{[key], :duplicate}`, a state it can't render at, as `cells/3`'s, a theme's
name its stylesheet can't hold, `{[:theme, :name], {:type, :word}}`, and `{[], {:type,
:keyword}}` for an `env` that isn't a keyword list.

# `to_json`

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

The JSON document, `{:ok, json}`, stamped `"$version"`, written by the JSON adapter
(`Macaw.Layers.Form`): a name as its string, a color by its tags, a time as `$time`, a
point as `$point`, an atom as `$atom`. A value JSON can't hold is refused at its path,
`{:type, :term}`, and a map key in a setting or param that isn't a string
`{:type, :name}`.

# `to_map`

```elixir
@spec to_map(t()) :: %{version: pos_integer(), surface: map()}
```

`%{version: current, surface: node}`: the surface's value as a document.

# `validate`

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

The static pass over a surface (spec/06 §3.4), with the host's registry and its sources
by name, each `{source, context}`: `{:ok, %Macaw.Surface.Validated{}}` or every fault at
once, by path from the surface. No I/O but each source's `describe`, and no viewer. An
entry of any other shape is `{:bad_source, name}` at its binding's source.

# `validate`

```elixir
@spec validate(
  t(),
  Macaw.Registry.t(),
  %{required(String.t()) =&gt; {Macaw.Data.Source.t(), term()}},
  keyword()
) :: {:ok, Macaw.Surface.Validated.t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

`validate/3` of a surface placed where `placement` says (spec/06 §2.6), the options
`Macaw.Template.placement/2` answers for a region: `kind:`, the kind a cell naming none
takes (`:content` by default), and `kinds:`, the kinds the place allows (every kind by
default). A cell's kind the place doesn't allow is `{:kind_not_allowed, kind, kinds}` at
`[:cells, name, :kind]`, beside the component's `{:kind_not_offered, kind, kinds}`. A
`kind:` that isn't a kind is `{[:placement, :kind], {:enum, kinds}}`, `kinds:` that
isn't a non-empty list of kinds `{[:placement, :kinds], {:type, :kinds}}`, another
option `{[:placement, key], :unknown_key}`.

# `values`

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

Each contained cell's value as `cells/3` builds it (spec/06 §3.6): `{:ok, %{name =>
value}}`, its faults `cells/3`'s. Built from a fetch, it is what every render of that
fetch at that state gives the cell, so a host builds it once and passes it as `values:`,
and no render runs a cell's transitions (init, each delivery, each bound setting, the
selection, the size) again. The host holds it, as it holds `fetched`: macaw keeps no
cache. A new fetch, a changed state or another env is a new `values/3`.

---

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