Macaw.State (macaw v0.6.0)

Copy Markdown View Source

The state of one validated surface (spec/03 §1.5): the value of each of its state sources, its declared ones and the two standard ones, selection and window.

A pure value: it holds no process, no clock and no reference to a host, so two states built from equal inputs are equal. A host builds one with new/2 and renders at it by giving it to Macaw.Surface.show/2, fetch/2 or render/3 as state:. A click reaches the host as one LiveView event, which event/3 reads, apply/2 applies and affected/2 says what to fetch and render again:

def handle_event("mw-event", params, socket) do
  with {:ok, event} <- Macaw.State.event(socket.assigns.validated, params, now()),
       {:ok, state, changed} <- Macaw.State.apply(socket.assigns.state, event) do
    {:noreply, show(socket, state, Macaw.State.affected(state, changed))}
  else
    {:error, _faults} -> {:noreply, socket}
  end
end

A surface's declared state sources are Macaw.State.Sources.

Summary

Types

A wire payload read/1 decoded, which event/3 takes in place of the params.

t()

A surface's state: surface its surface's name, declared its state sources by name, the declared and the per-cell ones (Macaw.Surface.Validated's state), values every state source's value by name, and what applying an event needs, copied from the validated surface: cells, each cell's declared events, standard writes and actions by its instance id, the validated surface's events index; params, each slot with request params bound to state, by its params' path; readers, each state's readers by its name, the validated surface's index, which affected/2 reads; initial, every value as new/2 built it, which persistence leaves unwritten; selection, the type of each identity field the cells writing selection agree on, which a restored selection is read by, by its own name and its canonical one; links, the surface's links, which selection is written through; identities, the validated surface's index of the cells the selection is handed to, which selection/2 reads; instances, the instance of each held scope (spec/03 §2.1), nil where the host gave none; resets, the names a view's and a page's reset take back, in name order, which reset/3 reads (spec/03 §1.3); overlays, each changed source's overlay by its name (spec/13 §3), held at :session scope, and policies the host's policy for each; feedback, a refused row's entered text and faults by the cell that sent it, which its next render shows at their fields.

Functions

What a change of the named states makes stale (spec/03 §1.5): %{fetch: [{cell, slot}], render: [cell]}, both in the surface's reading order. fetch is the slots whose request params are bound to a changed state, the slots of a cell with a setting bound to one (its order and budget read its settings), the slots bound to one (delivered again from it), and, when window changed, the slots whose source has a window field, of any kind; render is the cells with a setting bound to a changed state and every cell with a slot in fetch. A name the state has no source by is ignored.

Applies one event (spec/03 §1.5): {:ok, state, changed}, changed the names whose values changed, in name order, or {:error, faults} with nothing applied.

Applies one event to the states of the named scopes (spec/03 §1.5, §2.1): apply/2's answer, a write to a state of another scope neither judged nor applied, left to the process that holds it. apply/2 is apply/3 with every scope.

Reads the LiveView event a click sends (spec/03 §1.6) into an event: {:ok, %Macaw.Data.Event{}} with initiator: :visitor and time: now, or every fault at once. The payload is the viewer's, so each fault is a value, never a raise

An event path as an action holds it: {:ok, path}, its key or field a name read as its spelling, or :error for a term that is none of the five.

The five fields of an event an action may read (spec/03 §1.3): macaw_component's list, Macaw.Component.Declarations.event_paths/0, the one its default actions take, "key" and "field" standing for any name. They are the event's value, an entry of a map value, its identity, a field of a map identity, and a field of its row.

The state of a surface instance after a change to the region it fills (spec/06 §4): {:ok, state, changed}, every held value of a scope not in kept back at its initial value, the instance keys merged over the state's, and changed the names whose values changed, in name order. It is the state the instance holds before any owner's values reach it through put/2; kept is usually Macaw.Region.kept/2's answer.

A state source's value: {:ok, value}, or :error for a name the surface has no state source by.

The six scopes a server holds (spec/03 §2.1): every scope but :local, the browser's only. They are the scopes apply/3's scopes: may name.

A state's identity (spec/03 §2): {:ok, {scope, instance, name}}, or :error for a name the surface has no source by. The instance is the surface's name for :surface and :shared, the host's for :page, :region, :session and :viewer (new/2's instances:, nil where not given), and nil for :local, which the server never holds. A standard source and a per-cell one are {:surface, surface, name}. Two scopes with one name are two identities, and two values.

The instance a wire payload names (spec/03 §1.6): {:ok, instance}, or :error. A runtime holding several surfaces routes an "mw-event" by it without reading JSON itself; event/3 then reads the payload for the surface it names.

The state of a validated surface at every state source's initial value (spec/03 §1.5): {:ok, state}, or every fault at once, by path.

The state written into a host's persistence (spec/03 §3): persistence.store/3 of the carrier, under the surface's name, of every persisted state source whose value isn't its initial one, each as text. A source declared persist: false is never written; with Macaw.State.Persistence.None nothing is.

The preferences' names (spec/03 §1.7.3): shortcuts, theme, units and zone, standard state sources every surface holds, at :viewer scope when the host gives the viewer's instance and :session otherwise (Macaw.State.Preferences).

The state's preferences (spec/03 §1.7.3), %{theme, zone, units, shortcuts} as the state holds them: the theme's name for the host to render in (nil, its default), and the three every component's context carries as its preferences.

Puts values carried from an owner into the state (spec/03 §1.5, §2.1): {:ok, state, changed, dropped}, changed the names whose values changed, in name order. A mirror of a :shared owner puts the owner's values into its own state as they are published, and takes them whole when it joins (macaw_live 04 §4), of any held scope (spec/03 §2.1).

The instance a wire payload names, as instance/1 reads it, and the payload decoded: {:ok, instance, read}, or :error for whatever instance/1 answers :error for. A runtime holding several surfaces routes by the instance and hands read to event/3, so each event's JSON is decoded once (spec/03 §1.6).

Takes states back to where the page started (spec/03 §1.3): {:ok, state, changed, dropped}, changed the names whose values changed, in name order, or {:error, faults} with nothing reset. It is the reset action's effect, which apply/2 applies for a cell's action; a host calls it for a reset of its own.

The state with the values a host's persistence holds for it (spec/03 §3): {:ok, state, dropped}. The carrier is untrusted, so each value is read and judged as apply/2 judges an event's, and one that can't be used is left out and named in dropped, by path, never raised: a name the surface has no source by, {:unknown_state, name}; a source declared persist: false, :not_persisted; text not of the source's type, {:type, type}; a value outside its values, {:not_allowed, value}; a value bound into a request param that the source refuses, the param's faults. What loads that isn't a map is {[:state], {:type, :map}}, and nothing is restored.

The state restored as restore/3 restores it, each value also checked against the current legal values as a change is (spec/03 §3.2, spec/07 §2.2): {:ok, state, dropped}. A URL is anyone's to edit, so a value a control would never offer (a filter value the data doesn't hold, a theme the registry lacks) is dropped as a value outside its values is, and the state keeps its value.

The state with a snapshot's values (spec/03 §4): {:ok, state, dropped}. A snapshot is untrusted, saved under another schema perhaps, so each value is read and judged as restore/3 judges it, against each source's current declaration, and one that can't be used is left out and named in dropped, by path, never raised: restore/3's faults, and a source that no longer persists or is declared snapshot: false, :not_snapshotted. An entry that isn't a state and its value is {:type, :entry} at [:snapshot, :states, i]. A snapshot of another surface is {[:snapshot, :surface], {:surface_mismatch, name}}, and what isn't a snapshot {[:snapshot], {:type, :snapshot}}: nothing is restored.

The seven scopes a state source may declare (spec/03 §2.1): :local, :surface, :page, :region, :session, :viewer and :shared.

The selection a cell is handed, in its own fields (spec/03 §1.7): {:ok, selection}, or :error for a cell the selection isn't handed to. It is handed to each cell whose slots' sources declare identity fields: a :contained one through its bound/3 transition as bound(value, "selection", selection), a :pure one in its context's selection (spec/03 §1.7.7), and affected/2 renders those cells again when selection changes.

The state's snapshot (spec/03 §4): %Macaw.State.Snapshot{}, what persistence holds of the state, less each source declared snapshot: false: the current value of every persisted source that isn't its initial one, each a state and its text as persist/3 writes it, in name order. A value never changed restores at its source's initial value. It holds no identity, of a viewer or of anyone, so it restores for whoever restores it. A value with no text form (a theme color) isn't held.

The standard state sources' names (spec/03 §1.2): selection and window, which exist on every surface undeclared. Their types are macaw_component's (Macaw.Component.State.standard/0).

A standard state source's type: :identity for selection, :window for window.

A form a page sent, read and applied (spec/13 §3.5): the one seam for an add form's row, live or with no socket, and for a POST a remove control or a reset sends with no socket. The host routes it, a LiveView's handle_event("mw-submit", params, socket) or a controller's POST to the page's address, and macaw reads and applies it.

The LiveView event an add form sends (spec/13 §3.5), "mw-submit": a form's submission, read by submit/4, beside the "mw-event" every other control sends.

Every held state source's value, by name. A :local source is never held (spec/03 §2.1), so no :local name is among them.

One scope's values, by name (spec/03 §2.1): %{} for :local, never held, and for a scope the surface declares nothing at. An owner publishes from it when a mirror joins, and the mirror takes it whole with put/2. A standard source and a per-cell one are :surface's.

The states an event's actions would write (spec/03 §1.5): {:ok, [{scope, instance, name}]}, each state an action of the event's cell on its name sets, by its identity (identity/2), in the actions' declared order and each once, a cell's per-cell state among them (§1.3). Nothing is applied and the event's values aren't read, so the answer is the same whatever they hold; the standard writes (§1.2), which aren't actions, aren't in it. An event that sets nothing answers [].

Types

read()

@opaque read()

A wire payload read/1 decoded, which event/3 takes in place of the params.

t()

@type t() :: %Macaw.State{
  cells: %{required(String.t()) => map()},
  declared: %{required(String.t()) => Macaw.State.Source.t()},
  feedback: %{
    required(String.t()) => %{entered: map(), faults: [Macaw.Base.Fault.t()]}
  },
  identities: %{
    required(String.t()) => %{required(String.t()) => [String.t(), ...]}
  },
  initial: %{required(String.t()) => term()},
  instances: %{required(atom()) => String.t() | nil},
  links: %{required(String.t()) => String.t()},
  overlays: %{required(String.t()) => Macaw.Overlay.t()},
  params: [{[term(), ...], map()}],
  policies: %{required(String.t()) => Macaw.Overlay.Policy.t()},
  readers: %{required(String.t()) => map()},
  resets: %{view: [String.t()], page: [String.t()]},
  selection: %{required(String.t()) => atom()},
  surface: String.t(),
  values: %{required(String.t()) => term()}
}

A surface's state: surface its surface's name, declared its state sources by name, the declared and the per-cell ones (Macaw.Surface.Validated's state), values every state source's value by name, and what applying an event needs, copied from the validated surface: cells, each cell's declared events, standard writes and actions by its instance id, the validated surface's events index; params, each slot with request params bound to state, by its params' path; readers, each state's readers by its name, the validated surface's index, which affected/2 reads; initial, every value as new/2 built it, which persistence leaves unwritten; selection, the type of each identity field the cells writing selection agree on, which a restored selection is read by, by its own name and its canonical one; links, the surface's links, which selection is written through; identities, the validated surface's index of the cells the selection is handed to, which selection/2 reads; instances, the instance of each held scope (spec/03 §2.1), nil where the host gave none; resets, the names a view's and a page's reset take back, in name order, which reset/3 reads (spec/03 §1.3); overlays, each changed source's overlay by its name (spec/13 §3), held at :session scope, and policies the host's policy for each; feedback, a refused row's entered text and faults by the cell that sent it, which its next render shows at their fields.

Functions

affected(state, names)

@spec affected(t(), [String.t()]) :: %{
  fetch: [{String.t(), String.t()}],
  render: [String.t()]
}

What a change of the named states makes stale (spec/03 §1.5): %{fetch: [{cell, slot}], render: [cell]}, both in the surface's reading order. fetch is the slots whose request params are bound to a changed state, the slots of a cell with a setting bound to one (its order and budget read its settings), the slots bound to one (delivered again from it), and, when window changed, the slots whose source has a window field, of any kind; render is the cells with a setting bound to a changed state and every cell with a slot in fetch. A name the state has no source by is ignored.

It costs the readers of the changed names, never a walk of every reader: it reads their entries in the index the validated surface built once, Macaw.Surface.Validated's readers.

apply(state, event)

@spec apply(t(), Macaw.Data.Event.t()) ::
  {:ok, t(), [String.t()]} | {:error, [Macaw.Base.Fault.t(), ...]}

Applies one event (spec/03 §1.5): {:ok, state, changed}, changed the names whose values changed, in name order, or {:error, faults} with nothing applied.

What runs, in order: the event's standard writes (§1.2), from the cell whose instance id is the event's instance: an event with an identity writes selection, and one with no identity whose value is nil or a map writes window, each only from a component that declares writes of it; then that cell's actions on the event's name, in their declared order (§1.3), the later of two on one state winning. Only the paths an action names are read from the event. Every write is judged, and if any fails none is applied.

Its faults, every one at once: an instance that is no cell, {:unknown_instance, instance} at [:instance]; a name the component doesn't declare, {:undeclared, name} at [:name]; a value not of the state's type, {:type, type} at [:state, name]; one outside its values, {:not_allowed, value} there; a value bound into a request param that the source's declared param refuses, the param's faults at its path. No clock is read: the event's time is its own.

apply(state, event, opts)

@spec apply(t(), Macaw.Data.Event.t(), keyword()) ::
  {:ok, t(), [String.t()]} | {:error, [Macaw.Base.Fault.t(), ...]}

Applies one event to the states of the named scopes (spec/03 §1.5, §2.1): apply/2's answer, a write to a state of another scope neither judged nor applied, left to the process that holds it. apply/2 is apply/3 with every scope.

A :shared owner applies an event with scopes: [:shared], and a viewer applies its own with every other scope, sending the event to the owner (macaw_live 04 §4); the cell, the event's name and every write to a named scope are judged as apply/2 judges them.

opts: scopes:, a list of held scopes (held_scopes/0), every one by default; and legal:, the current legal values of each state source declaring values_from, by name, a set as Macaw.Surface.legal/2 reads them (or a list, spelled at each call), %{} by default (spec/07 §2.2). A write to such a state is checked against them at each change, a membership test of each value written: a value outside them is {:not_allowed, value} at [:state, name], and with none given {:unchecked, :values_from} there, so an unchecked change is never applied; nil is always legal. Opts that aren't a keyword list are {[], {:type, :keyword}}, an unknown opt {[key], :unknown_key}, a scopes: that isn't a list {[:scopes], {:type, :list}}, an entry that is no held scope, :local among them, {[:scopes, i], {:enum, held}}, a legal: that isn't a map {[:legal], {:type, :map}} and an entry that is neither a set nor a list {[:legal, name], {:type, :list}}; nothing is applied. A process applies with scopes: the scopes it holds and forwards a write of another's to its owner (spec/03 §2.1, macaw_live 04 §5).

iex> surface = Macaw.Surface.build!("wall", state: %{"pick" => %{type: :text, scope: :shared}}, cells: [{"macaw.table", source: "services", actions: [%{on: "sort", set: "pick", value: {:event, [:value, "sort"]}}]}])
iex> sources = %{"services" => {%Macaw.Test.Rows{}, nil}}
iex> {:ok, validated} = Macaw.Surface.validate(surface, Macaw.Registry.new!([Macaw.Builtin]), sources)
iex> {:ok, state} = Macaw.State.new(validated)
iex> {:ok, event} = Macaw.Data.Event.new(name: "sort", instance: "wall-table_services", value: %{"sort" => "v"}, initiator: :visitor, time: ~U[2026-11-11 12:00:00Z])
iex> {:ok, _owner, changed} = Macaw.State.apply(state, event, scopes: [:shared])
iex> changed
["pick"]
iex> {:ok, _viewer, changed} = Macaw.State.apply(state, event, scopes: [:surface])
iex> changed
[]

event(validated, params, now)

@spec event(Macaw.Surface.Validated.t(), term() | read(), DateTime.t()) ::
  {:ok, Macaw.Data.Event.t()} | {:error, [Macaw.Base.Fault.t(), ...]}

Reads the LiveView event a click sends (spec/03 §1.6) into an event: {:ok, %Macaw.Data.Event{}} with initiator: :visitor and time: now, or every fault at once. The payload is the viewer's, so each fault is a value, never a raise:

  • params that aren't a map holding "mw": {[], {:type, :event_params}};
  • a payload over 8 KiB: {[:mw], {:limit, :bytes, 8192, size}}, left unread; text that isn't JSON: {[:mw], :json}; a JSON value that isn't an object: {[:mw], {:type, :map}}; another key: :unknown_key at it; a missing instance or name: :required there;
  • an instance that is no cell: {:unknown_instance, id} at [:instance]; a name its component doesn't declare: {:undeclared, name} at [:name]; an identity that isn't null or an object of names to scalars: {:type, :identity} at [:identity].

This is the wire's inbound edge: the event holds terms, never JSON spelling, each value read by where it goes (spec/03 §1.6), the counterpart of what macaw_component's Client.event/3 writes:

  • a window write (no identity, an object or null value, from a component writing window): the keys "last", "from", "to", "as_of" and "box" read as atoms, the times as UTC DateTimes, a number from and to as it arrived, and a box's "west", "south", "east" and "north" as atoms; another key is :unknown_key at [:value, key] (a box's at [:value, "box", key]). Whether they make a window is apply/2's to judge;
  • an identity's field: by its type in the cell's slot schemas, where they agree, else by the type of a state an action sets from it;
  • a value an action sets, at :value or [:value, key]: by that state's type.

A time is read from ISO 8601 text with an offset, a point from [lon, lat], a color from CSS color text, and null is nil for each; a value not in its type's form is {:type, type} at its path. Strings, numbers, booleans, and lists and objects of them are terms as they are.

It costs the event's cell, never the surface's others: it reads that cell's entry in the index the validated surface built once, Macaw.Surface.Validated's events, so a runtime hands it the whole validated surface.

In place of the params it takes the payload read/1 decoded, and answers what it answers for the params they were read from, decoding nothing again.

event_path(arg1)

@spec event_path(term()) :: {:ok, {:event, atom() | [atom() | String.t()]}} | :error

An event path as an action holds it: {:ok, path}, its key or field a name read as its spelling, or :error for a term that is none of the five.

iex> Macaw.State.event_path({:event, [:value, :sort]})
{:ok, {:event, [:value, "sort"]}}
iex> Macaw.State.event_path({:event, :row})
:error

event_paths()

@spec event_paths() :: [{:event, atom() | [atom() | String.t()]}, ...]

The five fields of an event an action may read (spec/03 §1.3): macaw_component's list, Macaw.Component.Declarations.event_paths/0, the one its default actions take, "key" and "field" standing for any name. They are the event's value, an entry of a map value, its identity, a field of a map identity, and a field of its row.

iex> Macaw.State.event_paths()
[{:event, :value}, {:event, [:value, "key"]}, {:event, :identity},
 {:event, [:identity, "field"]}, {:event, [:row, "field"]}]

follow(state, kept, given \\ %{})

@spec follow(t(), [atom()], map()) ::
  {:ok, t(), [String.t()]} | {:error, [Macaw.Base.Fault.t(), ...]}

The state of a surface instance after a change to the region it fills (spec/06 §4): {:ok, state, changed}, every held value of a scope not in kept back at its initial value, the instance keys merged over the state's, and changed the names whose values changed, in name order. It is the state the instance holds before any owner's values reach it through put/2; kept is usually Macaw.Region.kept/2's answer.

A persistent region on navigation keeps its :region and :surface state and takes the new page's: follow(state, Macaw.Region.kept(region, :navigate), %{page: path}). A refilled region's returning content is new/2's state put its owners' values, which is follow(old, Macaw.Region.kept(region, :refill), %{}) when no owner's value changed.

Its faults, with nothing changed: a kept that isn't a list, {[:kept], {:type, :list}}; an entry that is no scope, {[:kept, i], {:enum, scopes}}; instances that new/2 refuses, its faults as new/2 gives them ([:instances | path]).

get(state, name)

@spec get(t(), String.t()) :: {:ok, term()} | :error

A state source's value: {:ok, value}, or :error for a name the surface has no state source by.

held_scopes()

@spec held_scopes() :: [atom(), ...]

The six scopes a server holds (spec/03 §2.1): every scope but :local, the browser's only. They are the scopes apply/3's scopes: may name.

identity(state, name)

@spec identity(t(), String.t()) ::
  {:ok, {atom(), String.t() | nil, String.t()}} | :error

A state's identity (spec/03 §2): {:ok, {scope, instance, name}}, or :error for a name the surface has no source by. The instance is the surface's name for :surface and :shared, the host's for :page, :region, :session and :viewer (new/2's instances:, nil where not given), and nil for :local, which the server never holds. A standard source and a per-cell one are {:surface, surface, name}. Two scopes with one name are two identities, and two values.

iex> surface = Macaw.Surface.build!("status", state: %{"filter" => %{type: :text, scope: :page}, "hover" => %{type: :time, scope: :local}}, cells: [{"macaw.table", source: "services"}])
iex> sources = %{"services" => {%Macaw.Test.Rows{}, nil}}
iex> {:ok, validated} = Macaw.Surface.validate(surface, Macaw.Registry.new!([Macaw.Builtin]), sources)
iex> {:ok, state} = Macaw.State.new(validated, instances: %{page: "/p/exio"})
iex> Macaw.State.identity(state, "filter")
{:ok, {:page, "/p/exio", "filter"}}
iex> Macaw.State.identity(state, "selection")
{:ok, {:surface, "status", "selection"}}
iex> Macaw.State.identity(state, "hover")
{:ok, {:local, nil, "hover"}}
iex> Macaw.State.get(state, "hover")
:error

instance(params)

@spec instance(term()) :: {:ok, String.t()} | :error

The instance a wire payload names (spec/03 §1.6): {:ok, instance}, or :error. A runtime holding several surfaces routes an "mw-event" by it without reading JSON itself; event/3 then reads the payload for the surface it names.

The payload is the viewer's, so anything else is :error, never a raise: params that aren't a map holding "mw", a payload over 8 KiB (left unread), text that isn't JSON, a JSON value that isn't an object, and an instance missing or not a string. Whether the instance is a cell of a surface is event/3's to judge.

iex> Macaw.State.instance(%{"mw" => ~s({"instance": "status-table_services", "name": "sort"})})
{:ok, "status-table_services"}
iex> Macaw.State.instance(%{"mw" => "not json"})
:error

new(validated, opts \\ [])

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

The state of a validated surface at every state source's initial value (spec/03 §1.5): {:ok, state}, or every fault at once, by path.

opts: host:, the host's values for the {:host, key} initials, a map of name to value, %{} by default; params:, the page's params for the {:param, name} initials, as Macaw.Page.params/2 reads them, %{} by default (spec/06 §5); instances:, the instance of each scope the host keys (spec/03 §2.1), a map of :page (the page's path), :region (the name of the region the surface fills), :session (the visit) and :viewer (the viewer) to a non-empty string, %{} by default, an instance not given nil; overlays:, the host's policy for each source the surface's add and remove actions change (spec/13 §3.1), a map of the source's name to a Macaw.Overlay.Policy or its keyword list, each such source's overlay built empty, every fault at [:overlays | path]: a changed source given none :required, a policy for a source nothing changes {:unknown_source, name}, a policy's own faults, and filters: that leave a declared param out (:required) or name an unknown param or field. A :local source is never held, so no host value or param is asked for it. Its faults, each at [:state, name, :initial]: a key the host doesn't give, {:missing_host, key}; a param not given, {:missing_param, name}; a value not of the type, {:type, type}; a value outside values, {:not_allowed, value}. An initial value bound into a request param that the source's declared param refuses is the param's faults at [:cells, cell, :slots, slot, :params | path] (a source shorthand's at [:cells, cell, :params | path]). Opts that aren't a keyword list are {[], {:type, :keyword}}, an unknown opt {[key], :unknown_key}, and a host: or params: that isn't a map {[key], {:type, :map}}. An instances: that isn't a map is {[:instances], {:type, :map}}, a key none of the four {[:instances, key], :unknown_key}, a value that isn't a non-empty string {[:instances, key], {:type, :string}}, and a :region that isn't a name {[:instances, :region], {:type, :name}}.

persist(state, persistence, carrier)

@spec persist(t(), module(), term()) :: term()

The state written into a host's persistence (spec/03 §3): persistence.store/3 of the carrier, under the surface's name, of every persisted state source whose value isn't its initial one, each as text. A source declared persist: false is never written; with Macaw.State.Persistence.None nothing is.

iex> surface = Macaw.Surface.build!("status", cells: [{"macaw.table", source: "services"}])
iex> sources = %{"services" => {%Macaw.Test.Rows{}, nil}}
iex> {:ok, validated} = Macaw.Surface.validate(surface, Macaw.Registry.new!([Macaw.Builtin]), sources)
iex> {:ok, state} = Macaw.State.new(validated)
iex> {:ok, event} = Macaw.Data.Event.new(name: "sort", instance: "status-table_services", value: %{"sort" => "v", "order" => "desc"}, initiator: :visitor, time: ~U[2026-11-11 12:00:00Z])
iex> {:ok, state, _changed} = Macaw.State.apply(state, event)
iex> Macaw.State.persist(state, Macaw.State.Persistence.Url, %{"page" => "2"})
%{"page" => "2", "status" => %{"table_services.order" => "desc", "table_services.sort" => "v"}}

preferences()

@spec preferences() :: [String.t(), ...]

The preferences' names (spec/03 §1.7.3): shortcuts, theme, units and zone, standard state sources every surface holds, at :viewer scope when the host gives the viewer's instance and :session otherwise (Macaw.State.Preferences).

preferences(state)

@spec preferences(t()) :: %{
  theme: String.t() | nil,
  zone: String.t(),
  units: atom(),
  shortcuts: map()
}

The state's preferences (spec/03 §1.7.3), %{theme, zone, units, shortcuts} as the state holds them: the theme's name for the host to render in (nil, its default), and the three every component's context carries as its preferences.

iex> surface = Macaw.Surface.build!("status", cells: [{"macaw.table", source: "services"}])
iex> sources = %{"services" => {%Macaw.Test.Rows{}, nil}}
iex> {:ok, validated} = Macaw.Surface.validate(surface, Macaw.Registry.new!([Macaw.Builtin]), sources)
iex> {:ok, state} = Macaw.State.new(validated, instances: %{viewer: "v1"})
iex> Macaw.State.preferences(state)
%{theme: nil, zone: "Etc/UTC", units: :as_posted, shortcuts: %{}}
iex> Macaw.State.identity(state, "units")
{:ok, {:viewer, "v1", "units"}}

put(state, values)

@spec put(t(), term()) :: {:ok, t(), [String.t()], [Macaw.Base.Fault.t()]}

Puts values carried from an owner into the state (spec/03 §1.5, §2.1): {:ok, state, changed, dropped}, changed the names whose values changed, in name order. A mirror of a :shared owner puts the owner's values into its own state as they are published, and takes them whole when it joins (macaw_live 04 §4), of any held scope (spec/03 §2.1).

The values are a map of name to value, already terms, and each is judged as restore/3 judges a stored one: one that can't be used is left out and named in dropped, by path, never raised, and every other is put. A name the surface has no source by is {:unknown_state, name} at [:state, name]; a value not of the type {:type, type} there; one outside the values {:not_allowed, value} there; one a bound request param refuses, the param's faults at its path; a :local source, never held, {:local_state, name} there. Values that aren't a map are {[:state], {:type, :map}}, and nothing is put.

read(params)

@spec read(term()) :: {:ok, String.t(), read()} | :error

The instance a wire payload names, as instance/1 reads it, and the payload decoded: {:ok, instance, read}, or :error for whatever instance/1 answers :error for. A runtime holding several surfaces routes by the instance and hands read to event/3, so each event's JSON is decoded once (spec/03 §1.6).

iex> {:ok, "status-table_services", _read} =
...>   Macaw.State.read(%{"mw" => ~s({"instance": "status-table_services", "name": "sort"})})
iex> Macaw.State.read(%{"mw" => "not json"})
:error

reset(state, target, opts \\ [])

@spec reset(t(), :view | :page | :all | [String.t()], keyword()) ::
  {:ok, t(), [String.t()], [Macaw.Base.Fault.t()]}
  | {:error, [Macaw.Base.Fault.t(), ...]}

Takes states back to where the page started (spec/03 §1.3): {:ok, state, changed, dropped}, changed the names whose values changed, in name order, or {:error, faults} with nothing reset. It is the reset action's effect, which apply/2 applies for a cell's action; a host calls it for a reset of its own.

The target is one of:

  • :view, every :surface state, the standard and per-cell ones among them;
  • :page, a page-level reset: every :surface state and every :page one;
  • :all, the view and the data: what :view takes back, and every overlay of the surface cleared, the visitor's rows added and removed (spec/13 §3.6);
  • a list of names, the named states, a :viewer preference such as "theme" among the ones it may name.

A :viewer preference is reset only when named, and a :session or :shared state never, even when named: they are the visit's and every viewer's, not the view's.

Each state goes back to its value in the state new/2 built: the declaration resolved, never a snapshot of a clock, so a relative window resets to one relative to each fetch's now. opts: legal:, the current legal values of each values_from state, by name, as apply/3 takes them. An initial no longer among them falls back to nil, always legal (a state's declared default is its literal initial, the value judged), and the drop is named in dropped, {:not_allowed, initial} at [:state, name]; an illegal value is never written. A state not given values for is reset to its initial as the fresh page holds it. apply/2 and apply/3 apply a reset action's fallback alike but answer only the changed names: this is where a host reads the drops.

Its faults: a target that is none of the four, {[:reset], {:type, :reset}}; a name the surface holds no state by, {:unknown_state, name} at [:reset, i]; a :local one, {:local_state, name}; a mirror, {:mirrored, name}; a :session or :shared one, {:reset_scope, scope}; a name given twice, {:duplicate, name}. Opts that aren't a keyword list are {[], {:type, :keyword}}, an unknown opt {[key], :unknown_key}, and a legal: apply/3 refuses its faults.

It costs the states it resets: a view's and a page's names are listed once, by new/2, and a named reset looks each name up, never walking every state the surface holds.

iex> surface = Macaw.Surface.build!("status", cells: [{"macaw.table", source: "services"}])
iex> sources = %{"services" => {%Macaw.Test.Rows{}, nil}}
iex> {:ok, validated} = Macaw.Surface.validate(surface, Macaw.Registry.new!([Macaw.Builtin]), sources)
iex> {:ok, fresh} = Macaw.State.new(validated)
iex> {:ok, event} = Macaw.Data.Event.new(name: "sort", instance: "status-table_services", value: %{"sort" => "v", "order" => "desc"}, initiator: :visitor, time: ~U[2026-11-11 12:00:00Z])
iex> {:ok, sorted, _changed} = Macaw.State.apply(fresh, event)
iex> {:ok, reset, changed, []} = Macaw.State.reset(sorted, :view)
iex> changed
["table_services.order", "table_services.sort"]
iex> reset == fresh
true

restore(state, persistence, carrier)

@spec restore(t(), module(), term()) :: {:ok, t(), [Macaw.Base.Fault.t()]}

The state with the values a host's persistence holds for it (spec/03 §3): {:ok, state, dropped}. The carrier is untrusted, so each value is read and judged as apply/2 judges an event's, and one that can't be used is left out and named in dropped, by path, never raised: a name the surface has no source by, {:unknown_state, name}; a source declared persist: false, :not_persisted; text not of the source's type, {:type, type}; a value outside its values, {:not_allowed, value}; a value bound into a request param that the source refuses, the param's faults. What loads that isn't a map is {[:state], {:type, :map}}, and nothing is restored.

restore(state, persistence, carrier, opts)

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

The state restored as restore/3 restores it, each value also checked against the current legal values as a change is (spec/03 §3.2, spec/07 §2.2): {:ok, state, dropped}. A URL is anyone's to edit, so a value a control would never offer (a filter value the data doesn't hold, a theme the registry lacks) is dropped as a value outside its values is, and the state keeps its value.

opts: legal:, the current legal values by name, as apply/3 takes them, %{} by default. A values_from state's value must be among its entry, {:not_allowed, value} at [:state, name] when it isn't, and {:unchecked, :values_from} there with no entry, so a value that wasn't checked is never restored; a state of any other kind given an entry (the theme preference, given the registry's themes) is checked against it too. nil is always legal. Opts that aren't a keyword list are {:error, [{[], {:type, :keyword}}]}, an unknown opt {[key], :unknown_key}, and a legal: apply/3 refuses its faults, with nothing restored.

iex> rows = [%{"t" => ~U[2026-11-18 12:00:00Z], "v" => 1, "host" => "a"}]
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> {:ok, state} = Macaw.State.new(validated)
iex> legal = %{"host" => MapSet.new(["a"])}
iex> {:ok, _state, []} = Macaw.State.restore(state, Macaw.State.Persistence.Url, %{"status" => %{"host" => "a"}}, legal: legal)
iex> {:ok, kept, dropped} = Macaw.State.restore(state, Macaw.State.Persistence.Url, %{"status" => %{"host" => "z"}}, legal: legal)
iex> {Macaw.State.get(kept, "host"), dropped}
{{:ok, nil}, [{[:state, "host"], {:not_allowed, "z"}}]}

restore_snapshot(state, snapshot)

@spec restore_snapshot(t(), term()) :: {:ok, t(), [Macaw.Base.Fault.t()]}

The state with a snapshot's values (spec/03 §4): {:ok, state, dropped}. A snapshot is untrusted, saved under another schema perhaps, so each value is read and judged as restore/3 judges it, against each source's current declaration, and one that can't be used is left out and named in dropped, by path, never raised: restore/3's faults, and a source that no longer persists or is declared snapshot: false, :not_snapshotted. An entry that isn't a state and its value is {:type, :entry} at [:snapshot, :states, i]. A snapshot of another surface is {[:snapshot, :surface], {:surface_mismatch, name}}, and what isn't a snapshot {[:snapshot], {:type, :snapshot}}: nothing is restored.

scopes()

@spec scopes() :: [atom(), ...]

The seven scopes a state source may declare (spec/03 §2.1): :local, :surface, :page, :region, :session, :viewer and :shared.

selection(state, cell)

@spec selection(t(), String.t()) ::
  {:ok, nil | [%{fields: [String.t(), ...], value: term()}]} | :error

The selection a cell is handed, in its own fields (spec/03 §1.7): {:ok, selection}, or :error for a cell the selection isn't handed to. It is handed to each cell whose slots' sources declare identity fields: a :contained one through its bound/3 transition as bound(value, "selection", selection), a :pure one in its context's selection (spec/03 §1.7.7), and affected/2 renders those cells again when selection changes.

The selection is nil, nothing selected, or one entry per field of the identity, in name order, [%{fields: [field], value: value}]: each with the cell's identity fields that are that field through the surface's links (spec/03 §7), the field itself among them, and the value. A cell with no field for some field of the identity is handed nil, since none of its rows can hold it. A scalar selection names no field: it is one entry over the cell's fields of its one identity, and nil for a cell of several.

snapshot(state)

@spec snapshot(t()) :: Macaw.State.Snapshot.t()

The state's snapshot (spec/03 §4): %Macaw.State.Snapshot{}, what persistence holds of the state, less each source declared snapshot: false: the current value of every persisted source that isn't its initial one, each a state and its text as persist/3 writes it, in name order. A value never changed restores at its source's initial value. It holds no identity, of a viewer or of anyone, so it restores for whoever restores it. A value with no text form (a theme color) isn't held.

iex> surface = Macaw.Surface.build!("status", cells: [{"macaw.table", source: "services"}])
iex> sources = %{"services" => {%Macaw.Test.Rows{}, nil}}
iex> {:ok, validated} = Macaw.Surface.validate(surface, Macaw.Registry.new!([Macaw.Builtin]), sources)
iex> {:ok, fresh} = Macaw.State.new(validated)
iex> {:ok, event} = Macaw.Data.Event.new(name: "sort", instance: "status-table_services", value: %{"sort" => "v", "order" => "desc"}, initiator: :visitor, time: ~U[2026-11-11 12:00:00Z])
iex> {:ok, state, _changed} = Macaw.State.apply(fresh, event)
iex> snapshot = Macaw.State.snapshot(state)
iex> snapshot.states
[%{state: "table_services.order", value: "desc"}, %{state: "table_services.sort", value: "v"}]
iex> {:ok, restored, []} = Macaw.State.restore_snapshot(fresh, snapshot)
iex> restored.values == state.values
true

standard()

@spec standard() :: [String.t(), ...]

The standard state sources' names (spec/03 §1.2): selection and window, which exist on every surface undeclared. Their types are macaw_component's (Macaw.Component.State.standard/0).

standard_type(name)

@spec standard_type(String.t()) :: atom()

A standard state source's type: :identity for selection, :window for window.

submit(state, validated, params, opts)

@spec submit(t(), Macaw.Surface.Validated.t(), term(), keyword()) ::
  {:ok, t(), list()}
  | {:refused, t(), [Macaw.Base.Fault.t(), ...]}
  | {:error, [Macaw.Base.Fault.t(), ...]}

A form a page sent, read and applied (spec/13 §3.5): the one seam for an add form's row, live or with no socket, and for a POST a remove control or a reset sends with no socket. The host routes it, a LiveView's handle_event("mw-submit", params, socket) or a controller's POST to the page's address, and macaw reads and applies it.

  • The carried changes: a page with no socket keeps the visitor's changes held :visit in its own forms, "mw-changes"; they are read back first, every row judged again by its schema and the host's rules, as an untrusted carrier is (spec/03 §3.2), and one that can't be used is left out.
  • An add form's row, "mw-row", each field's text by name: read at this edge by the source's schema, as persistence's text is (spec/03 §3.2), then applied as the add action of the cell and event the payload "mw" names. A refusal is the state holding the cell's feedback, the text entered and the faults by field, which its next render shows at each field.
  • Any other payload is read by event/3 and applied by apply/3.

It answers {:ok, state, changed} as apply/3 does, the cell's feedback cleared; {:refused, state, faults}, nothing applied but the carried changes and the feedback, each fault by path ([:row, field] at its field); or {:error, faults} for params it can't read: params that aren't a map holding "mw", {[], {:type, :event_params}}; event/3's faults of the payload; a row sent to an event that adds nothing, {["mw-row"], {:no_add, name}}. opts: now: (required), the event's time, and legal:, as apply/3 takes it; opts that aren't a keyword list are {[], {:type, :keyword}}, an unknown opt {[key], :unknown_key}, a missing or bad now: {[:now], :required} or {[:now], {:type, :time}}.

submit_event()

@spec submit_event() :: String.t()

The LiveView event an add form sends (spec/13 §3.5), "mw-submit": a form's submission, read by submit/4, beside the "mw-event" every other control sends.

values(state)

@spec values(t()) :: %{required(String.t()) => term()}

Every held state source's value, by name. A :local source is never held (spec/03 §2.1), so no :local name is among them.

values(state, scope)

@spec values(t(), atom()) :: %{required(String.t()) => term()}

One scope's values, by name (spec/03 §2.1): %{} for :local, never held, and for a scope the surface declares nothing at. An owner publishes from it when a mirror joins, and the mirror takes it whole with put/2. A standard source and a per-cell one are :surface's.

writes(state, event)

@spec writes(t(), Macaw.Data.Event.t()) ::
  {:ok, [{atom(), String.t() | nil, String.t()}]}
  | {:error, [Macaw.Base.Fault.t(), ...]}

The states an event's actions would write (spec/03 §1.5): {:ok, [{scope, instance, name}]}, each state an action of the event's cell on its name sets, by its identity (identity/2), in the actions' declared order and each once, a cell's per-cell state among them (§1.3). Nothing is applied and the event's values aren't read, so the answer is the same whatever they hold; the standard writes (§1.2), which aren't actions, aren't in it. An event that sets nothing answers [].

It reads the event's cell by its instance id, as apply/2 does, so its cost is that cell's actions, never a walk of every cell. A runtime that holds some scopes reads here which writes are another's to apply (§2.1). Its faults are apply/2's for an event no cell declares: {:unknown_instance, instance} at [:instance] and {:undeclared, name} at [:name].

iex> surface = Macaw.Surface.build!("wall", state: %{"pick" => %{type: :text, scope: :session}}, cells: [{"macaw.table", source: "services", actions: [%{on: "sort", set: "pick", value: {:event, [:value, "sort"]}}]}])
iex> sources = %{"services" => {%Macaw.Test.Rows{}, nil}}
iex> {:ok, validated} = Macaw.Surface.validate(surface, Macaw.Registry.new!([Macaw.Builtin]), sources)
iex> {:ok, state} = Macaw.State.new(validated, instances: %{session: "s1"})
iex> {:ok, event} = Macaw.Data.Event.new(name: "sort", instance: "wall-table_services", value: %{"sort" => "v"}, initiator: :visitor, time: ~U[2026-11-11 12:00:00Z])
iex> Macaw.State.writes(state, event)
{:ok, [{:session, "s1", "pick"}]}