Current section
Files
Jump to
Current section
Files
live_slice
README.md
README.md
# live_slice
live_slice is a small client-side store for Phoenix LiveView, built for plain JavaScript hooks. Hooks on the
same page share state through it synchronously, without a websocket round trip, and the server stays in
charge of what it needs to know. It suits any page where several client-side pieces react to the same state:
a selection shared by a table and a detail panel, filters, a chart or map viewport, a draft, or a list that
must keep working offline. The [demo](guides/demo.md) shows some of them: two MapLibre maps (one drawn by
hand, one by the maplibrex components), an offline-capable task list and a note that several people edit at
once.
A bridge hook and the `LiveSlice` Elixir module connect a store to its LiveView:
- **mirror** sends declared keys to the server, debounced per key;
- **server actions** change the store at once and let the LiveView confirm or roll back the change, or
answer one made on data that changed since with a **conflict**;
- **patch** merges small server state into the store, and **invalidate** makes the client fetch large data
over plain HTTP;
- **persistence** keeps selected keys in IndexedDB across reloads, and the **offline queue** holds server
actions while disconnected and replays them in order;
- **DOM bindings** let server-rendered elements react to the store and keep their classes across patches;
- **collaborative keys** hold a Yjs document whose concurrent and offline edits merge instead of conflicting.
Optional entries live outside the core: `live_slice/data` loads large datasets in chunks over HTTP (see
[Large data](guides/large-data.md)), `live_slice/maplibre` binds a store to a MapLibre GL JS map (see
[MapLibre binding](guides/maplibre.md)), and `live_slice/sw` with `live_slice/offline` let a page open with no
network at all (see [Offline cold start](guides/offline-cold-start.md)), and `live_slice/crdt` binds collaborative keys,
with `LiveSlice.CRDT` on the optional Elixir dependency `y_ex` (see [Collaborative keys](guides/collaborative-keys.md)).
Status: prototype. It is published on [Hex](https://hex.pm/packages/live_slice), with its JavaScript inside the
package; it is not on npm. The API may change between releases. [CHANGELOG.md](CHANGELOG.md) lists what each release changes. Coming from 0.1.0, read
[Upgrading from 0.1.0 to 0.2.0](guides/upgrading.md) first.
## Example
A store created in `app.js`, read by a hook and bound to a LiveView. The LiveView receives the `filters` key
300 ms after the client last changed it, and the rows follow `selectedId` in the browser, with no round trip.
```js
// assets/js/app.js
import { createStore, getStore, LiveSliceHook } from "live_slice";
createStore("catalog", {
state: { selectedId: null, filters: { query: "" } },
actions: {
select: (_state, id) => ({ selectedId: id }),
search: (state, query) => ({ filters: { ...state.filters, query } }),
},
});
// Any hook reads and changes the store synchronously, for example:
// getStore("catalog").actions.select(42) or getStore("catalog").actions.search("tea").
const SelectionLabel = {
mounted() {
const render = (id) => {
this.el.textContent = id === null ? "Nothing selected" : `Selected: ${id}`;
};
render(getStore("catalog").getState().selectedId);
this.unsubscribe = getStore("catalog").subscribe((state) => state.selectedId, render);
},
destroyed() {
this.unsubscribe();
},
};
const liveSocket = new LiveSocket("/live", Socket, {
params: { _csrf_token: csrfToken },
hooks: { LiveSlice: LiveSliceHook, SelectionLabel },
});
```
```elixir
defmodule MyAppWeb.CatalogLive do
use MyAppWeb, :live_view
use LiveSlice, store: :catalog, mirror: [filters: [debounce: 300]]
@impl true
def mount(_params, _session, socket) do
{:ok, assign(socket, rows: MyApp.Catalog.search(""))}
end
@impl true
def render(assigns) do
~H"""
<LiveSlice.bridge id="catalog-store" module={__MODULE__} />
<p id="selection" phx-hook="SelectionLabel" phx-update="ignore"></p>
<ul>
<li
:for={row <- @rows}
id={"row-#{row.id}"}
data-store-match="catalog.selectedId"
data-store-value={row.id}
data-store-class="font-semibold"
>
{row.name}
</li>
</ul>
"""
end
# Each mirrored key arrives as decoded JSON: validate it like any client input.
@impl LiveSlice
def handle_store(:filters, %{"query" => query}, socket) when is_binary(query) do
{:noreply, assign(socket, rows: MyApp.Catalog.search(query))}
end
def handle_store(:filters, _invalid, socket), do: {:noreply, socket}
end
```
[Getting started](guides/getting-started.md) builds a fuller version of this example step by step.
## Installation
Requirements: Elixir 1.16+, Phoenix LiveView 1.2. The JavaScript has no runtime dependencies. Collaborative keys
also need `{:y_ex, "~> 0.13"}` in the app's deps and Yjs (`npm install yjs`), passed in by the app.
### Elixir
Add the dependency from Hex:
```elixir
# mix.exs
defp deps do
[
{:live_slice, "~> 0.2.1"}
# or a release tag: {:live_slice, github: "CountlinkX-Solutions/live_slice", tag: "v0.2.1"}
# or a local checkout: {:live_slice, path: "../live_slice"}
]
end
```
While the version is 0.x, a new minor version (0.3.0) may change the API: read its entry in
[CHANGELOG.md](CHANGELOG.md) before running `mix deps.update live_slice`.
With the git form, `branch: "main"` in place of `tag:` follows unreleased changes.
### JavaScript
The package name is `live_slice`; its `package.json` exports `live_slice` (`assets/js/live_slice/index.js`)
and the optional entries `live_slice/data` (`assets/js/live_slice/data.js`), `live_slice/maplibre`
(`assets/js/live_slice/maplibre.js`), `live_slice/sw` (`assets/js/live_slice/sw.js`, for a service worker),
`live_slice/offline` (`assets/js/live_slice/offline.js`), `live_slice/crdt`
(`assets/js/live_slice/crdt.js`) and, for application tests, `live_slice/testing`
(`assets/js/live_slice/testing.js`, see [Testing an application](guides/testing.md)). esbuild resolves them
through the `exports` map
(checked with the demo's npm `file:` link below).
- **Hex or git dependency.** Mix puts the package, or the repository at the tag, into `deps/live_slice`, the
JavaScript included: the files under `assets/js/live_slice` ship in the Hex package and are tracked in git,
and need no build, so the JavaScript always matches the Elixir side. The esbuild configuration generated by Phoenix sets `NODE_PATH`
to include `deps`, so `import ... from "live_slice"` (and the optional entries) resolves without further
setup or `npm install`. Node itself does not read `NODE_PATH` for ES modules, so tests that run under
`node --test` (see [Testing an application](guides/testing.md)) need the checkout linked:
`{ "dependencies": { "live_slice": "file:../deps/live_slice" } }` in `assets/package.json`, then
`npm install --prefix assets` after `mix deps.get`.
- **Path dependency.** A path dependency is not copied into `deps`, so link it with npm. In
`assets/package.json` (the path is relative to `assets/`):
```json
{ "dependencies": { "live_slice": "file:../../live_slice" } }
```
then run `npm install --prefix assets`. The demo in `demo/` does this with `"live_slice": "file:../.."`.
## Guides
| Guide | What it covers |
|---|---|
| [Getting started](guides/getting-started.md) | Creating a store, using it from hooks, binding a LiveView and mirroring keys. |
| [Patch, invalidate and DOM bindings](guides/patch-and-invalidate.md) | Server state merged into the store, large data fetched over HTTP, entry patches, coalescing, `data-store-*` bindings. |
| [Server actions](guides/server-actions.md) | Optimistic actions that the LiveView accepts or refuses; the confirmed state and reducers. |
| [Persistence and the offline queue](guides/persistence.md) | Keys kept in IndexedDB, actions queued while offline, failed pushes and cancelling. |
| [Tabs, connection and store lifecycle](guides/tabs-and-connection.md) | Tabs sharing a store, reconnects and live navigation, the connection status, stores that a hook creates and removes. |
| [Conflicts](guides/conflicts.md) | Actions based on a version of the data, and what happens when it changed since. |
| [Collaborative keys](guides/collaborative-keys.md) | Yjs documents that merge concurrent and offline edits, served by `LiveSlice.CRDT`. |
| [Offline cold start](guides/offline-cold-start.md) | A service worker and the offline mount, so pages open with no network. |
| [Large data](guides/large-data.md) | `live_slice/data`: chunks over HTTP, a persistent chunk cache, binary columns. |
| [MapLibre binding](guides/maplibre.md) | `live_slice/maplibre`: a store bound to a MapLibre GL JS map, with or without maplibrex. |
| [Testing an application](guides/testing.md) | `live_slice/testing`: a fake LiveView, IndexedDB and tabs, and a reference server for collaborative keys. |
| [Demo](guides/demo.md) | The Phoenix application in `demo/` and how to run it. |
| [Upgrading from 0.1.0 to 0.2.0](guides/upgrading.md) | Changed defaults and stored or wire shapes. |
| [Known limits](guides/known-limits.md) | What the library does not do, or does only in part. |
## Tests
From the repository root:
```sh
# Library
mix deps.get && mix test
npm install && npm test # node --test "assets/test/**/*.test.js"
# Demo (after mix setup in demo/)
(cd demo && mix test)
(cd demo/assets && npm test) # node --test "test/**/*.test.js"
```
`assets/test/fixtures/columns.bin` and `columns.json` are written by the Elixir tests of `LiveSlice.Columns`
and read by the JavaScript decoder tests. The Elixir test fails when the encoder no longer produces the checked
in bytes; after an intended format change, rewrite them with
`LIVE_SLICE_UPDATE_FIXTURES=1 mix test test/live_slice/columns_test.exs`.
The JavaScript tests of collaborative keys sync real Yjs documents with the reference server of
`live_slice/testing` (see [Testing an application](guides/testing.md)), a peer that answers the protocol as
`LiveSlice.CRDT` does; the Elixir tests drive `LiveSlice.CRDT` with y_ex documents standing in for browsers.
## Contributing
Bug reports and pull requests are welcome; see
[CONTRIBUTING.md](https://github.com/CountlinkX-Solutions/live_slice/blob/main/CONTRIBUTING.md). Report security issues
privately, as [SECURITY.md](https://github.com/CountlinkX-Solutions/live_slice/blob/main/SECURITY.md) describes.
## License
MIT. See [LICENSE](LICENSE).