# `LiveSlice`
[🔗](https://github.com/CountlinkX-Solutions/live_slice/blob/v0.2.1/lib/live_slice.ex#L1)

Server side of live_slice: binds a LiveView to a client-side store.

The store lives in the browser (see `assets/js/live_slice`) and is shared by
plain LiveView hooks without a server round trip. This module connects it to
the LiveView in four ways:

  * **mirror** (client to server): keys declared in `:mirror` are pushed by
    the bridge hook, debounced per key, and delivered to the LiveView's
    `c:handle_store/3` callback. Keys that are not declared never reach it.
    The LiveView is expected to mount with the store's initial values; keys
    that already differ when the bridge mounts (for example after a live
    navigation) are pushed at once, and every mirrored key is pushed again
    after a reconnect, since the new LiveView process starts from scratch.
  * **server actions** (client to server and back): the client applies a
    store action optimistically and sends it to the LiveView's
    `c:handle_action/4` callback, whose reply confirms or rolls back the
    change on the client. Action names are declared in `:actions`.
  * **patch** (server to client): `patch/3` merges small state into the store,
    and `put_entries/5`, `merge_entries/5`, `delete_entries/5`,
    `append_items/5` and `prepend_items/5` change entries inside one key.
  * **invalidate** (server to client): `invalidate/4` tells the client to
    fetch a URL over HTTP and put the JSON result in the store, which keeps
    large datasets off the LiveView channel.

Datasets too large for one response are loaded in chunks by the optional
JavaScript entry `live_slice/data` (`createChunkLoader`), from routes of the
app that can encode their chunks with `LiveSlice.Columns`. The server tells
those loaders about a new version of the dataset with `patch/3` of a small
key that the loader follows (its `versionKey` option), for example
`LiveSlice.patch(socket, :map, %{featuresVersion: version})`: no other
server event is needed.

## Usage

    defmodule MyAppWeb.CatalogLive do
      use MyAppWeb, :live_view
      use LiveSlice, store: :catalog, mirror: [:selected_id, filters: [debounce: 300]]

      def mount(_params, _session, socket) do
        {:ok, assign(socket, selected_id: nil, filters: %{})}
      end

      def render(assigns) do
        ~H"""
        <LiveSlice.bridge id="catalog-store" module={__MODULE__} />
        ...
        """
      end

      # Called with the key as an atom; must return {:noreply, socket}.
      @impl LiveSlice
      def handle_store(:filters, filters, socket) when is_map(filters) do
        {:noreply, assign(socket, filters: filters)}
      end

      def handle_store(:selected_id, id, socket) do
        {:noreply,
         socket
         |> assign(selected_id: id)
         |> LiveSlice.invalidate(:catalog, :details, url: ~p"/products/#{id}")}
      end
    end

On the client, create the store before connecting the LiveSocket and
register the bridge hook:

    import { createStore, LiveSliceHook } from "live_slice";

    createStore("catalog", {
      state: { selected_id: null, filters: {}, details: null },
      actions: { select: (_state, id) => ({ selected_id: id }) },
    });

    new LiveSocket("/live", Socket, { hooks: { LiveSlice: LiveSliceHook } });

With `persist`, the store also keeps chosen keys and its pending server
actions in the browser across reloads; see `createStore` in
`assets/js/live_slice/store.js`.

## Server actions

A store action written as `{ apply, server }` in JavaScript changes the
store at once and is sent to the LiveView as the action named `server`:

    createStore("cart", {
      state: { items: [], count: 0 },
      actions: {
        addItem: {
          apply: (state, sku) => ({ items: [...state.items, sku], count: state.count + 1 }),
          server: "add_item",
        },
      },
    });

    // Resolves when the server accepts the call, rejects with the reason
    // when it refuses it (the change is rolled back either way first).
    getStore("cart").actions.addItem("tea").catch((reason) => console.warn(reason));

The LiveView declares the action and implements `c:handle_action/4`:

    defmodule MyAppWeb.CartLive do
      use MyAppWeb, :live_view
      use LiveSlice, store: :cart, actions: [:add_item]

      @impl LiveSlice
      def handle_action(:add_item, [sku], %{id: mutation_id}, socket) when is_binary(sku) do
        # The mutation id lets MyApp.Carts skip a call it already applied.
        case MyApp.Carts.add_item(socket.assigns.cart, sku, mutation_id) do
          {:ok, cart} ->
            # Accept, with the server's view merged over the client state.
            # Return {:ok, socket} to accept and keep the optimistic change.
            {:ok, %{items: cart.items, count: length(cart.items)}, assign(socket, cart: cart)}

          {:error, :out_of_stock} ->
            # Refuse: the client rolls the change back.
            {:error, "out_of_stock", socket}
        end
      end
    end

Render the bridge with `module={__MODULE__}`: it then carries a
`data-actions` marker, and only a bridge with that marker sends the
store's server actions, to the LiveView that rendered it. To handle a
store's actions on every page without repeating them, define them once
with `LiveSlice.Actions` and attach that module with `on_mount`. When two
LiveViews on one page declare actions for the same store, the bridge
mounted first sends them and the other one logs an error and waits until
the first is destroyed.

Every `"live_slice:action"` event is answered, since the client waits for
the reply: with `%{ok: true}`, `%{ok: true, state: state}`,
`%{ok: false, reason: reason}` or, for a conflict (see "Conflicts" below),
`%{ok: false, conflict: true, reason: reason, state: state}`. The library
refuses an undeclared action with the reason `"unknown_action"`, an action
for another store with `"unknown_store"`, and a malformed payload with
`"invalid_payload"`, and logs those at debug level. A state or reason that
cannot be sent as JSON is left out or replaced (see `c:handle_action/4`)
instead of crashing the LiveView after the call took effect. A
`handle_action/4` that raises crashes the LiveView like any other
callback, and one that returns anything else raises an `ArgumentError`.

Delivery is at least once. The client sends one call at a time, in call
order, and keeps calls made while disconnected (and, for persisted stores,
across reloads) until the LiveView answers them. A call whose reply was
lost, for example to a disconnect, is sent again with the same `meta.id`
and a higher `meta.attempt`, so the server may run it twice: make handlers
idempotent with `meta.id` where that matters. A call that got no reply
after the store's `maxAttempts` sends (3 by default) is no longer sent, so
a call that crashes the LiveView is not replayed forever: the client keeps
it as failed, and the application may send it again later with the same
`meta.id` and `meta.base` (and the next `meta.attempt`), so look the id up
before anything else: a retry must get the answer of a first send that was
applied, not a conflict with it. A store created with `keepFailed: false`
rolls such a call back with the reason `"push_failed"` instead.

## Conflicts

`handle_action/4` decides whether a call is accepted. To refuse a call made
on data that changed since the client saw it, give the action a `base` in
JavaScript, the version it is based on, read from the store's confirmed
state when the action is called:

    renameTask: {
      apply: (state, id, title) => ({ tasks: rename(state.tasks, id, title) }),
      server: "rename_task",
      base: (state, id) => state.tasks.find((task) => task.id === id)?.lock_version ?? null,
    },

It arrives as `meta.base` (present when the client sent one; read it with
`meta[:base]`, which is `nil` otherwise). Compare it with the current
version and return `{:conflict, state, socket}` or
`{:conflict, state, reason, socket}` when they differ: the client rolls
the call back, merges `state` over its confirmed state (the server wins)
and reports the conflict, or resubmits the call when the action's
`onConflict` resolver says so. The reason is `"conflict"` unless given.

For a record with an integer `lock_version` (or an `updated_at` stamp
compared the same way), with Ecto:

    def handle_action(:rename_task, [id, title], %{id: mutation_id} = meta, socket) do
      task = Tasks.get_task!(id)

      cond do
        # 1. A call already applied (its reply was lost) gets its first
        #    answer again, before anything else: its own first run moved
        #    the version, which must not turn the retry into a conflict.
        Tasks.applied?(mutation_id) ->
          {:ok, %{tasks: Tasks.list_tasks()}, socket}

        # 2. Then the version check.
        meta[:base] != task.lock_version ->
          {:conflict, %{tasks: Tasks.list_tasks()}, "stale", socket}

        true ->
          changeset =
            task
            |> Task.changeset(%{title: title})
            |> Ecto.Changeset.optimistic_lock(:lock_version)

          case Tasks.update_task(changeset, mutation_id) do
            # 3. Reply with the new version, so the client's next edit of
            #    the same record is based on it.
            {:ok, _task} -> {:ok, %{tasks: Tasks.list_tasks()}, socket}
            # The row changed between the check and the update.
            {:error, :stale} -> {:conflict, %{tasks: Tasks.list_tasks()}, "stale", socket}
            {:error, _changeset} -> {:error, "invalid_title", socket}
          end
      end
    end

`Tasks.update_task/2` stands for an update that records the mutation id in
the same transaction and turns `Ecto.StaleEntryError` into
`{:error, :stale}`. The client moves the base of later calls of its queue
that were based on the same version when an earlier one is confirmed, so
return the new version in the reply state (as above): a patch of this
LiveView that comes after the reply, such as a broadcast to every LiveView
of the record, arrives too late for that. A conflict merges nothing automatically: the
client keeps the server's state, and merging concurrent edits is the
application's choice, in the resolver or in the handler.

## Collaborative keys

A key declared in `:collaborative` holds the JSON of a Yjs document that
several people edit at once, also offline: their changes merge instead of
being accepted or refused (see the Collaborative keys guide for when to
use one). The client binds it with `createCollaborativeKey` from
`live_slice/crdt`; the server keeps one `LiveSlice.CRDT` process per
document, which needs the optional dependency `y_ex` and a
`{LiveSlice.CRDT, name: ...}` child in the supervision tree.

    use LiveSlice, store: :notes, collaborative: [notes: [server: MyApp.CRDT]]

    # Which document the key syncs in this LiveView: the client names the
    # document it holds, and any other name is refused.
    @impl LiveSlice
    def crdt_document(:notes, socket), do: "notes:#{socket.assigns.note.id}"

    # Who may read (sync and receive changes) and write (send changes).
    @impl LiveSlice
    def authorize_crdt("notes:" <> _id, :read, socket), do: socket.assigns.member?
    def authorize_crdt("notes:" <> _id, :write, socket), do: socket.assigns.editor?

Both callbacks are required with `:collaborative`. They are called on every
sync, on every update the client sends, and before every change of the
document is pushed to the client, so keep them cheap (read assigns). A
client whose LiveView names another document now, or that may no longer
read, gets no further change: the LiveView leaves the document and tells the
client, which stops syncing the key until its next connection. A client
refused because `c:crdt_document/2` named another document or none (a
`sync1` that arrived before the assigns it depends on, or a document the
LiveView left) waits instead: after each render, when the callback names
that document, the LiveView tells the client to sync it again.
`LiveSlice.CRDT.reauthorize/1` runs these checks at once, for example right
after a revocation changed the assigns they read. Authorization is per
document and direction: the server cannot look into an update and refuse
part of it, so rules about what the data may contain belong on normal keys
with server actions. A client may also deliver, in the background, the
offline changes of documents it does not show when the LiveView accepts
them with `c:accept_crdt_delivery/3` (refused by default).
`LiveSlice.CRDT.delete/2` deletes a document: its
clients discard their copies, told through the same checks, instead of
restoring it.

## Options

  * `:store` (required) - the store name, an atom or a string. It must not
    contain a `.`, since DOM bindings address keys as `"store.key"`.
  * `:mirror` - the keys pushed to the server. Each entry is either a key
    (`:selected_id`) or a key with options (`filters: [debounce: 300]`).
    `:debounce` is in milliseconds and defaults to `0`. Keys are store keys
    as written in JavaScript, so `selectedId` is mirrored as `:selectedId`.
  * `:actions` - the server action names the client may call, as atoms
    (`[:add_item, :remove_item]`). A LiveView that declares actions must
    define `c:handle_action/4`.
  * `:collaborative` - the collaborative keys, each a key (`:notes`, synced
    with the `LiveSlice.CRDT` server named `LiveSlice.CRDT`) or a key with
    options (`notes: [server: MyApp.CRDT]`). A collaborative key cannot also
    be mirrored. Requires `y_ex` and the callbacks above.
  * `:coalesce` - `[quiet: ms, max_wait: ms]` or `true`: every patch this
    LiveView pushes, to any store, waits with the ones that follow it (see
    "Coalescing" in `patch/4`), unless a call says `coalesce: false`. Add
    `keep: [key]` for keys whose every value must reach the client.

`use LiveSlice` must come after `use Phoenix.LiveView` and can be used once
per LiveView. It attaches a `:handle_event` lifecycle hook (via `on_mount`)
that consumes every `"live_slice:mirror"` and `"live_slice:action"` event
(and `"live_slice:crdt"` with collaborative keys, plus the messages of their
document processes, through a `:handle_info` hook, and an `:after_render`
hook for the clients that wait for a document name) before the LiveView's own
callbacks, so existing `handle_event/3` and `handle_info/2` clauses keep
working. Mirror events for another store, for undeclared keys
or with a malformed payload are dropped; action events of that kind are
refused as described above. Client-sent keys and action names are never
converted to new atoms.

# `action_meta`

```elixir
@type action_meta() :: %{
  :id =&gt; String.t(),
  optional(:attempt) =&gt; pos_integer(),
  optional(:base) =&gt; term()
}
```

Information about a server action call: `:id` is the client-generated
mutation id, the same on every delivery of the call, and `:attempt` counts
the client's pushes of it from 1 (present when the client sends it, as the
live_slice bridge does). `:base` is the decoded JSON value of the version
the call is based on, present when the client sent one (an action that
declares `base`; see "Conflicts"), so `meta[:base]` is `nil` otherwise.

# `store`

```elixir
@type store() :: atom() | String.t()
```

A store name: an atom or a non-empty string without dots.

# `accept_crdt_delivery`
*optional* 

```elixir
@callback accept_crdt_delivery(
  key :: atom(),
  doc_name :: String.t(),
  socket :: Phoenix.LiveView.Socket.t()
) ::
  boolean()
```

Whether this LiveView's client may deliver, in the background, the changes
it made to `doc_name` for the collaborative `key` while it did not show it
(`deliverUnsentDocuments` in `live_slice/crdt`): a document other than the
one `c:crdt_document/2` names. Optional; without it every background
delivery is refused with `"not_deliverable"`. A document it accepts still
needs `c:authorize_crdt/3` to allow both `:read` and `:write`. Called for
each step of a delivery.

    @impl LiveSlice
    def accept_crdt_delivery(:notes, "notes:" <> _id, _socket), do: true
    def accept_crdt_delivery(_key, _doc_name, _socket), do: false

# `authorize_crdt`
*optional* 

```elixir
@callback authorize_crdt(
  doc_name :: String.t(),
  access :: :read | :write,
  socket :: Phoenix.LiveView.Socket.t()
) :: boolean()
```

Whether this LiveView's client may `:read` the document (sync it and receive
its changes) or `:write` it (send changes). Called on every sync (both),
every update the client sends (`:write`) and before every change of the
document is pushed to the client (`:read`); anything but `true` refuses.

# `crdt_document`
*optional* 

```elixir
@callback crdt_document(key :: atom(), socket :: Phoenix.LiveView.Socket.t()) ::
  String.t() | nil
```

Returns the name of the document that the collaborative `key` syncs for
this LiveView, or `nil` when it has none. A client that names another
document is refused with `"wrong_document"` (`"no_document"` for `nil`), and
is told to sync again (`step: "resync"`) after the first render in which
this callback names the document it asked for. Called on every sync and
update, before every change of the document is pushed to the client, and
after each render while a client waits for a name.

# `handle_action`
*optional* 

```elixir
@callback handle_action(
  action :: atom(),
  args :: list(),
  meta :: action_meta(),
  socket :: Phoenix.LiveView.Socket.t()
) ::
  {:ok, Phoenix.LiveView.Socket.t()}
  | {:ok, map(), Phoenix.LiveView.Socket.t()}
  | {:error, term(), Phoenix.LiveView.Socket.t()}
  | {:conflict, map(), Phoenix.LiveView.Socket.t()}
  | {:conflict, map(), term(), Phoenix.LiveView.Socket.t()}
```

Runs a server action called by the client.

`action` is one of the atoms declared in `:actions`, `args` is the list of
arguments the client passed (decoded JSON), and `meta` holds the mutation
`:id`, which stays the same if the client sends the call again,
`:attempt`, which counts those sends from 1, and `:base`, the version the
call is based on, when the client sent one (see `t:action_meta/0`).

Return `{:ok, socket}` to accept the call, `{:ok, state, socket}` to accept
it and merge the map `state` over the client's confirmed state (the server
wins), or `{:error, reason, socket}` to refuse it, which rolls the call back
on the client. Return `{:conflict, state, socket}` or
`{:conflict, state, reason, socket}` to refuse a call made on data that
changed since (see "Conflicts" in the module documentation): the client
rolls it back, merges the map `state` over its confirmed state and reports
a conflict with `reason` (`"conflict"` by default), or resubmits it when
the action's resolver says so. `state` and `reason` are sent to the client
as JSON: a `state` that is a struct or cannot be encoded is left out of the
reply (an accepted call is still accepted), and a `reason` that cannot be
encoded, such as a tuple or an `Ecto.Changeset`, is replaced with
`"invalid_reason"`. Both are logged with `Logger.error/1`. Socket changes
are kept in every case.

# `handle_store`
*optional* 

```elixir
@callback handle_store(
  key :: atom(),
  value :: term(),
  socket :: Phoenix.LiveView.Socket.t()
) ::
  {:noreply, Phoenix.LiveView.Socket.t()}
```

Receives a mirrored store value pushed by the client.

`key` is one of the atoms declared in `:mirror`; `value` is the decoded
JSON value (`nil` when the client value was `null` or `undefined`).

# `append_items`

```elixir
@spec append_items(
  Phoenix.LiveView.Socket.t(),
  store(),
  atom() | String.t(),
  list(),
  keyword()
) ::
  Phoenix.LiveView.Socket.t()
```

Appends `items` to the list under `key` in the client store. With
`limit: n`, only the last `n` items of the list are kept. A key that holds
no list on the client is treated as an empty one.

    LiveSlice.append_items(socket, :log, :lines, new_lines, limit: 500)

# `bridge`

Renders the bridge hook element for a store.

Pass `module` to render the options of the LiveView that uses `LiveSlice`
and renders the bridge, so they are declared only once:

    <LiveSlice.bridge id="catalog-store" module={__MODULE__} />

The element carries the `:store`, the `:mirror` keys and, when the
LiveView declares `:actions`, a `data-actions` marker: only a bridge with
that marker sends the store's server actions, and only to this LiveView.
Collaborative keys are listed in `data-channels` (`{"crdt": ["notes"]}`):
only a bridge that lists a key syncs its document, with this LiveView.
Mirror events and server actions reach the LiveView whose template renders
the bridge, so pass that LiveView's own module.

When a `LiveSlice.Actions` module attached to the LiveView handles the same
store's actions, name it with `actions`, so one bridge both mirrors and
sends the queue: `<LiveSlice.bridge id="map-store" module={__MODULE__}
actions={MyAppWeb.MapActions} />`.

Or pass only `store`, for another store whose patches, invalidates and DOM
bindings this page uses:

    <LiveSlice.bridge id="table-store" store={:table} />

Such a bridge mirrors nothing and sends no server actions: those need a
LiveView that declares them with `use LiveSlice`. Passing `mirror` raises.

The client must register the bridge hook as `LiveSlice`.

## Attributes

* `id` (`:string`) (required)
* `module` (`:atom`) - the LiveView module that uses LiveSlice and renders this bridge. Defaults to `nil`.
* `store` (`:any`) - the store name, when `module` is not given. Defaults to `nil`.
* `actions` (`:atom`) - a LiveSlice.Actions module of the same store, attached to this LiveView, that sends its actions. Defaults to `nil`.
* Global attributes are accepted.

# `delete_entries`

```elixir
@spec delete_entries(
  Phoenix.LiveView.Socket.t(),
  store(),
  atom() | String.t(),
  list(),
  keyword()
) ::
  Phoenix.LiveView.Socket.t()
```

Removes entries from the map under `key` in the client store, by their keys.

    LiveSlice.delete_entries(socket, :dashboard, :team, [member.id])

# `flush_patches`

```elixir
@spec flush_patches(Phoenix.LiveView.Socket.t(), store() | nil) ::
  Phoenix.LiveView.Socket.t()
```

Pushes the coalesced patches that wait (see `patch/4`), of every store or
of `store` only, at once.

# `invalidate`

```elixir
@spec invalidate(Phoenix.LiveView.Socket.t(), store(), atom() | String.t(), keyword()) ::
  Phoenix.LiveView.Socket.t()
```

Tells the client store named `store` to fetch `url` and put the decoded JSON
under `key`.

Use it for data too large for the LiveView channel; the client fetches it
over plain HTTP. A newer invalidate for the same key supersedes an older one
still in flight. Coalesced patches of the store that wait (see `patch/4`)
are pushed first.

The bridge only fetches `http:` or `https:` URLs of the page's origin
(relative URLs resolve against the page); it refuses any other URL with a
console error, unless the client allows it with
`createLiveSliceHook({ allowUrl })`.

## Options

  * `:url` (required) - the URL to fetch, typically a path to a JSON
    controller route.

## Examples

    LiveSlice.invalidate(socket, :catalog, :products, url: ~p"/products?version=#{version}")

## Conditional fetches and client parameters

The bridge remembers the `ETag` of each response and sends it as
`If-None-Match` the next time it fetches the same URL while the key still
holds that response's value; a `304 Not Modified` keeps the value. Answer
with `send_json/3`, which does both sides. The client may add query
parameters from its store's state (`defineInvalidation` in the JavaScript
library), and fetches the URL again when they change, so the controller
reads them to narrow what it sends:

    def index(conn, params) do
      tasks = MyApp.Tasks.list(team: params["team"], status: params["status"])
      LiveSlice.send_json(conn, tasks)
    end

# `merge_entries`

```elixir
@spec merge_entries(
  Phoenix.LiveView.Socket.t(),
  store(),
  atom() | String.t(),
  map(),
  keyword()
) ::
  Phoenix.LiveView.Socket.t()
```

Merges fields into entries of the map under `key` in the client store:
`entries` maps each entry's key to a map of fields, merged over the entry's
fields (an entry that is missing or not a map is set to the given map).

    LiveSlice.merge_entries(socket, :dashboard, :team, %{member.id => %{inspections: 4}})

# `patch`

```elixir
@spec patch(Phoenix.LiveView.Socket.t(), store(), map(), keyword()) ::
  Phoenix.LiveView.Socket.t()
```

Merges `state` into the client store named `store`.

Meant for small state such as a selection. The client never echoes these
values back through `:mirror`.

    socket |> LiveSlice.patch(:catalog, %{selected_id: 42})

## Coalescing

A LiveView that patches often (a dashboard fed by every change of a team)
can let its patches wait together:

    LiveSlice.patch(socket, :dashboard, %{as_of: now}, coalesce: [quiet: 400, max_wait: 2_000])

The first patch of a store after a quiet time leads: it and every other
patch of the store that the same callback makes go out together, as one
`live_slice:patch`, at the end of that callback (when the LiveView starts
handling its next message; the callback sends one to itself). The patches
of later callbacks wait until `:quiet` ms pass without another, but never
more than `:max_wait` ms after the first of them, and go out as one
`live_slice:patch`, merged in order: a later whole key replaces an earlier
one and the entry operations on it (`put_entries/5` and the others), and
operations on one key are combined where the result is the same. The
store's state ends where the separate patches would have left it, but the
client writes each key once, so its `reducers` and listeners do not see the
values in between. A held key goes out with the key (atom or string) the
latest patch of it gave, as a patch pushed at once does. No timer of the
application is needed: the first coalesced patch attaches `:handle_info`,
`:handle_event` and `:handle_async` hooks to the LiveView.

  * `coalesce: true` uses the LiveView's `use LiveSlice, coalesce: [...]`
    timing, or `[quiet: 200, max_wait: 1_000]`; a keyword list sets
    `:quiet` and `:max_wait` (milliseconds); `false` pushes at once.
  * `keep: keys` (in the same keyword list) names keys whose every value
    must reach the client, such as a delta key that a client reducer folds:
    a patch that writes such a key again while an earlier value waits
    starts a new `live_slice:patch`, and the held ones go out together, in
    order. A call's keyword list keeps the LiveView's `:keep` unless it
    gives its own.
  * `use LiveSlice, coalesce: [quiet: ..., max_wait: ...]` (or `true`)
    coalesces every patch of the LiveView, of any store, unless the call
    says `coalesce: false`.
  * A patch that does not coalesce takes what waits for its store along,
    so the client gets everything in order. What waits for a store also
    goes out before the reply to one of its server actions (with the
    patches of that store the handler made), before `invalidate/4` of the
    store, and `flush_patches/2` sends it at once. Each of them first sends
    the leading patches of the current callback, of any store. An event
    the callback pushes itself goes before its leading patches unless it
    calls `flush_patches/2` first.
  * A patch made with a LiveComponent's socket is pushed at once (a
    component cannot hold patches for its LiveView), so it may overtake
    what the LiveView holds for the same store.
  * During the static render nothing waits.
  * What still waits when the LiveView process ends is not sent, also
    when a callback returns with `push_navigate/2` or `redirect/2`, its
    own leading patches included (no hook runs after it, and the client's
    store survives a live navigation). Call `flush_patches/2` before
    navigating in the same callback: LiveView sends the socket's events
    before it navigates.

The entry functions (`put_entries/5`, `merge_entries/5`,
`delete_entries/5`, `append_items/5`, `prepend_items/5`) take the same
`:coalesce` option. An option these functions do not know raises an
`ArgumentError` that names it.

# `prepend_items`

```elixir
@spec prepend_items(
  Phoenix.LiveView.Socket.t(),
  store(),
  atom() | String.t(),
  list(),
  keyword()
) ::
  Phoenix.LiveView.Socket.t()
```

Prepends `items` (in their order) to the list under `key` in the client
store. With `limit: n`, only the first `n` items of the list are kept: a
feed, newest first.

    LiveSlice.prepend_items(socket, :dashboard, :feed, new_entries, limit: 50)

# `put_entries`

```elixir
@spec put_entries(
  Phoenix.LiveView.Socket.t(),
  store(),
  atom() | String.t(),
  map(),
  keyword()
) ::
  Phoenix.LiveView.Socket.t()
```

Sets entries of the map under `key` in the client store, leaving its other
entries as they are: `entries` maps each entry's key to its new value.

A patch replaces a key whole; this sends only the entries that changed, and
the client merges them into the confirmed value of the key (see "Patching
entries" in the Patch, invalidate and DOM bindings guide). Entry keys may
be atoms, strings or integers and arrive as strings, as JSON object keys do. A key that holds no map on the
client is treated as an empty one.

    LiveSlice.put_entries(socket, :dashboard, :districts, %{"North" => district})

# `send_json`

```elixir
@spec send_json(Plug.Conn.t(), term() | (-&gt; term()), keyword()) :: Plug.Conn.t()
```

Sends `data` as JSON with an `ETag`, or `304 Not Modified` without a body
when the request's `If-None-Match` names that tag: the client already holds
this data (the bridge sends the tag of the value it holds, see
`invalidate/4`).

The tag is a weak one made from a hash of the JSON, or from `:version`
when given (a string, an integer, a `DateTime`, `NaiveDateTime` or `Date`
that changes whenever the data does, such as an `updated_at` or a
counter): then `data` may be a zero-arity function, called only when the
data is sent, so an unchanged dataset is neither loaded nor encoded. A
version with characters an entity tag cannot carry as they are (a comma,
a quote, a space) is hashed into the tag. `If-None-Match` is compared
weakly, as RFC 9110 requires (`"x"` matches `W/"x"`), and `*` matches.

    def tasks(conn, _params) do
      version = MyApp.Tasks.version()
      LiveSlice.send_json(conn, fn -> MyApp.Tasks.list() end, version: version)
    end

---

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