# Patch, invalidate and DOM bindings

Steps 4 and 5 of the catalog example that starts in [Getting started](getting-started.md).

## 4. Send state to the client: patch and invalidate

```elixir
# Small state: merged into the store. Not echoed back through the mirror.
socket |> LiveSlice.patch(:catalog, %{selectedId: 42})

# Large data: the client fetches the URL and stores the decoded JSON under :products.
socket |> LiveSlice.invalidate(:catalog, :products, url: ~p"/api/products?#{[query: "tea"]}")
```

`invalidate/4` sends only the store, key and URL over the websocket. The bridge fetches the URL with
`accept: application/json` and the browser's normal same-origin credentials, so protect the endpoint like
any other route. A newer invalidate for the same key aborts the older request. A failed request or a non-2xx
response is reported with `console.error` and leaves the store unchanged.

The bridge only fetches `http:` and `https:` URLs of the page's own origin; relative URLs resolve against
the page. Any other URL (another origin, `data:`, `blob:`, a malformed one) is refused with `console.error`
and changes nothing, unless you allow it when you create the hook:

```js
createLiveSliceHook({ allowUrl: (url) => url.origin === "https://tiles.example.com" });
```

`allowUrl` receives the resolved `URL` of every URL the default refuses, and the bridge fetches it only when
`allowUrl` returns `true`.

### Conditional fetches and client parameters

The bridge remembers the `ETag` of each invalidate response and sends it back as `If-None-Match` the next
time it fetches the same URL while the key still holds the value that came with it (not after a patch or a
write changed it, and not for another URL). A `304 Not Modified` keeps the value; a 304 to a request that
carried no `If-None-Match` is reported with `console.error` and changes nothing. `If-None-Match` goes only to
URLs of the page's origin: on another origin (one `allowUrl` accepts) the header makes the browser send a CORS
preflight, which a data host may refuse. Opt such a host in once it allows the header
(`Access-Control-Allow-Headers: If-None-Match`, and `Access-Control-Expose-Headers: ETag`):

```js
createLiveSliceHook({
  allowUrl: (url) => url.origin === "https://data.example.com",
  conditional: (url) => url.origin === "https://data.example.com",
});
```

`LiveSlice.send_json/3` answers both ways:

```elixir
def products(conn, params) do
  # A weak ETag from a hash of the JSON, or from a version you keep (then the data is built only when sent).
  version = Catalog.version()
  LiveSlice.send_json(conn, fn -> Catalog.list(query: params["query"]) end, version: version)
end
```

A version is a non-empty string, an integer, a `DateTime`, `NaiveDateTime` or `Date` (an `updated_at`); any other
value raises. 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 HTTP requires, and `*` matches any version.

The client can narrow the request with parameters from its store's state, and fetch it again when they
change:

```js
import { defineInvalidation } from "live_slice";

defineInvalidation(store, "products", {
  params: (state) => ({ category: state.category, page: state.page }), // added to the server's URL
  debounce: 200, // ms after the last change (200 by default)
});
```

Each invalidate of the key fetches the server's URL with these query parameters (replacing any of the same
name; `null` and `undefined` are left out, an array repeats the name). Once the server invalidated the key on
the page, a change of the parameters fetches that URL again with the new ones, `debounce` ms after the last
change; a fetch still running for the key is aborted, so the last one wins, and a change that leaves the
parameters as they were fetches nothing and does not postpone a fetch that waits for changed parameters. An
invalidate that arrives meanwhile fetches with the current parameters, and the waiting fetch is dropped. The
server URL still decides the endpoint; the controller reads the
parameters and must check them like any other input. `defineInvalidation` returns a function that removes
the options.

### Patching entries

`patch/3` replaces each key it names. For a large map or list of which one entry changed, send only that
entry:

```elixir
socket
|> LiveSlice.put_entries(:dashboard, :districts, %{"North" => north})     # set entries of a map
|> LiveSlice.merge_entries(:dashboard, :team, %{member.id => %{issues: 4}}) # merge fields into entries
|> LiveSlice.delete_entries(:dashboard, :team, [gone.id])                # remove entries
|> LiveSlice.prepend_items(:dashboard, :feed, [entry], limit: 50)        # newest first, at most 50
|> LiveSlice.append_items(:log, :lines, lines, limit: 500)               # oldest first, the last 500
```

| Function | Wire operation | On the client |
|---|---|---|
| `put_entries(socket, store, key, %{entry => value})` | `["put", key, entries]` | `{...value, ...entries}`: each entry set to its new value, others kept |
| `merge_entries(socket, store, key, %{entry => fields})` | `["merge", key, entries]` | each entry's fields merged over its fields; a missing or non-object entry is set to the fields |
| `delete_entries(socket, store, key, [entry])` | `["delete", key, keys]` | the entries removed |
| `append_items(socket, store, key, items, limit: n)` | `["append", key, items, n?]` | items added at the end; with `limit`, only the last `n` kept |
| `prepend_items(socket, store, key, items, limit: n)` | `["prepend", key, items, n?]` | items added at the start, in their order; with `limit`, only the first `n` kept |

- Each call pushes `live_slice:patch` with `{store, ops: [operation]}`, so only the changed entries travel. A
  patch event may carry both `state` and `ops`: the whole keys are merged first, then the operations run in
  order, in one write of the store (subscribers are called once). Coalesced patches (see
  [Coalescing patches](#coalescing-patches)) combine them this way.
- Entry keys may be strings, atoms or integers and arrive as strings, like any JSON object key. A key that holds
  no plain object on the client (for `put`, `merge`, `delete`) or no array (for `append`, `prepend`) counts as
  an empty one. A malformed operation is reported with `console.error` and skipped; the others still apply.
- The operations apply to the **confirmed** value of the key, like a patch: pending server actions stay applied on
  top and a rollback leaves what the server sent (see [The confirmed state](server-actions.md#the-confirmed-state)). `reducers`
  run for the keys they change.
- A mirrored key changed by operations is not pushed back: the operations applied to what the server held count
  as what it holds now. A local change of the key that still waits in its debounce is therefore pushed as usual,
  with the operations' entries in it. A persisted key is written like any confirmed value.
- Unchanged entries keep their identity on the client and changed ones are new objects, so a `subscribe` on one
  entry (`(state) => state.team[id]`) is called only when that entry changed.

### Coalescing patches

A LiveView that patches on every change of shared data (a dashboard fed by a whole team) can let its patches
wait together, without timers of its own:

```elixir
# Per LiveView: every patch of this LiveView, to any store, is coalesced.
use LiveSlice, store: :map, actions: [...], coalesce: [quiet: 400, max_wait: 2_000]

# Or per call, in any LiveView (also one that does not `use LiveSlice`):
LiveSlice.merge_entries(socket, :dashboard, :team, %{id => member}, coalesce: [quiet: 400, max_wait: 2_000])
LiveSlice.patch(socket, :dashboard, %{asOf: now}, coalesce: true) # the LiveView's timing, or 200/1000 ms
```

- **Leading edge, quiet time, maximum wait.** Per store, the first patch after a quiet time leads: it and every
  other patch of the store that the same callback makes (a `handle_info/2` that patches a feed, a district and a
  member) go out together, merged into one `live_slice:patch`, at the end of that callback. 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 then go out as one `live_slice:patch`. A burst of 20 changes becomes 2 pushes; a steady stream, one
  push per `max_wait`.
- **The end of a callback.** LiveView runs no hook after a callback, so the leading patches go out when the
  LiveView starts handling its next message (an event, a message or an async result); the leading callback
  sends a message to itself so that there is one. In practice they reach the client in the WebSocket message
  that follows the callback's own (its render and the events it pushed itself), right after it. A push that goes
  out at once in the leading callback (a patch with `coalesce: false`, the reply to a server action,
  `invalidate/4`, `flush_patches`) sends them first, so pushes keep the order of the calls that made them; a
  later patch of that callback joins the next leading push. An event the callback pushes itself with
  `push_event/3` goes before them: call `LiveSlice.flush_patches(socket)` first when it must follow them (that
  also puts them in the callback's own message). Calls, casts and `handle_params/3` are not seen as new
  callbacks: their patches join a leading push that has not gone yet.
- **Merged in order.** Whole keys (`state`) and entry operations (`ops`, see [Patching entries](#patching-entries))
  are merged so the store's state ends where the separate patches would have left it: a later whole key replaces
  an earlier one and the operations on it that waited; an operation is combined with the latest one on the same
  key where the result is the same (puts merge, appends join under the same limit, and so on). What is lost is
  the values in between: the client writes each key once, so `reducers`, `subscribe` and `subscribeConfirmed`
  see only the last value of a key that was patched twice. A held key goes out with the key the latest patch
  of it gave, an atom or a string, as a patch pushed at once does (and so do the fields of combined merges): on
  the wire both are the same JSON name, and a server-side test (`assert_push_event`) sees the keys it patched
  whether they waited or not.
- **Keys whose every value matters.** A delta key that the client folds into a larger one (see
  [The confirmed state](server-actions.md#the-confirmed-state)) must not lose a value. Name it in `keep`:

  ```elixir
  use LiveSlice, store: :assets, coalesce: [quiet: 400, max_wait: 2_000, keep: [:latestChanges]]
  # or per call
  LiveSlice.patch(socket, :assets, %{latestChanges: delta}, coalesce: [keep: [:latestChanges]])
  ```

  A patch that writes a kept key again (whole or with entry operations) while an earlier value of it waits
  starts a new `live_slice:patch`; the held patches still go out together, in order, in the same message, and
  the client applies them one after the other, running `reducers` for each value. `keep` names keys of any store
  and applies to the LiveView's patches when given to `use LiveSlice`; a call's own `coalesce: [...]` keeps
  those keys unless it gives `keep` itself.
- **Order with other pushes.** A patch with `coalesce: false` (or without coalescing) takes what waits for its
  store along, in one push. What waits for a store also goes out before the reply to one of its server actions,
  and so do the patches of that store that `handle_action/4` itself makes, so the reply's state is applied after
  them. `invalidate/4` sends what waits for its store first. `LiveSlice.flush_patches(socket)` (or
  `flush_patches(socket, store)`) sends what waits at once. Each of them first sends the leading patches of the
  current callback, of any store.
- **LiveComponents.** A patch made with a LiveComponent's socket is pushed at once: a component cannot hold
  patches for its LiveView. It may overtake patches the LiveView holds for the same store; when that order
  matters, `send/2` the change to the LiveView (`send(self(), ...)`) and patch there.
- **How.** The first coalesced patch attaches `:handle_info`, `:handle_event` and `:handle_async` hooks to the
  LiveView: they see each callback start, and receive the timers (`Process.send_after`) and the message to self;
  the application writes no `handle_info` clause. During the static render nothing waits.
- **Tests.** `assert_push_event/3` waits for the push, so it sees the leading patches. A test that reads the
  pushes as soon as `render/1` returns sees them after a second `render/1` (each one waits for the LiveView to
  handle what came before it, and the leading patches go out when it handles the message to itself).
- **When the LiveView ends**, what still waits is not sent. That includes `push_navigate/2` and `redirect/2`,
  also for the leading patches of the callback that navigates: the library sees no hook after it, and the
  JavaScript store survives a live navigation, so the next page keeps the store without them, unless its
  LiveView patches those keys again. Call `LiveSlice.flush_patches(socket)` before navigating in the same
  callback; LiveView sends the socket's events before it navigates:

  ```elixir
  def handle_event("save", params, socket) do
    socket = socket |> save(params) |> LiveSlice.flush_patches()
    {:noreply, push_navigate(socket, to: ~p"/tasks")}
  end
  ```

  After a crash or a lost connection the client mounts a new LiveView, which sends its state. Keep `max_wait`
  short for data that matters.

## 5. DOM bindings

An element with `data-store-match="store.key"`, `data-store-value` and `data-store-class` gets the classes
in `data-store-class` while `String(state[key]) === data-store-value`, and loses them otherwise. Numbers
therefore match their attribute strings (`42` matches `"42"`).

The bridge re-applies bindings after every LiveView patch, including on elements a patch adds or whose
`data-store-value` changed. With `onBeforeElUpdated` wired into the LiveSocket `dom` option, the classes are
also put on the incoming element before the morph, so a patch never removes them, not even for one style
recalculation. That matters for classes that drive CSS transitions.

To use a custom fetch for `invalidate` (extra headers, instrumentation) or to allow other URLs (step 4),
register `createLiveSliceHook({ fetch, allowUrl })` instead of `LiveSliceHook`.
