# Demo

`demo/` is a Phoenix 1.8 application (no database) with six LiveViews, linked from the navigation (a sidebar,
or a Menu button on a narrow screen), and an overview at `/overview` that lists them by group. Every page says
what it shows, lists the steps to try, frames the live example beside the library state it reads, and ends
with the calls of live_slice it uses. The `map`, `tasks` and `notes` stores are
created in `app.js`, so they survive a live navigation between the pages; the `/maplibrex` and `/logs` pages
create and remove their own.

- **Map (server table)** (`/`): a MapLibre map, a table of the features in view, a detail panel and layer toggles share the
  `map` store over a deterministic dataset of 200,000 synthetic points (`Demo.Features`, kept as columns,
  about 7 MB, sorted by quadkey so that every tile is one range of ids). The selection stays in the browser,
  and the map hides a layer turned off by itself. The viewport and the layer visibility are mirrored; the
  server answers with the table rows of the visible layers in view, or an empty state. The map hook loads
  the features of the viewport with a chunk loader by Web Mercator tiles (`tileChunks`, at the map's zoom
  rounded down) from `GET /api/features/tile/:z/:x/:y?v=version`, in the binary columnar format, keeps them
  in IndexedDB (`createChunkCache`, 64 MiB), joins them into one GeoJSON source (keeping the points shown
  while a view that shares no tile with the last one loads: `keepPrevious`), publishes the decoded tiles
  as well (`chunksKey: "featureTiles"`), and shows the loader's status (tiles loaded, read from IndexedDB,
  fetched over HTTP, failed). The server patches the dataset
  version into the store on mount (the store keeps the last one in IndexedDB, for an offline start), and
  **Publish a new version** patches a new one into every open map page,
  which fetches its tiles again. A counter shows store updates against mirror events and HTTP fetches. The
  map hook adds its own source and layers and hands the viewport, map clicks and the selection highlight to
  `bindMap`. `GET /api/features?bbox=w,s,e,n` still returns GeoJSON, for comparison.
- **Map (client table)** (`/map-client`): the same map, tiles, layer toggles, detail panel and counters on
  the same `map` store, with nothing mirrored (`use LiveSlice, store: :map`: its bridge only receives the
  dataset version patches). The table is a plain hook under `phx-update="ignore"`
  (`assets/js/client_table.js`) that lists the features of the visible layers in view, the first 50 in id
  order and their count, as `/` does, in one pass over the typed-array columns of the loaded tiles (the
  `featureTiles` the map's loader publishes), at most once per animation frame, and shows how long each
  pass took. A pan, a layer toggle, a selection or a hover
  sends nothing over the websocket. Until every tile of the view has loaded, the count covers only the
  loaded ones. The two pages share the `map` store, so a live navigation between them keeps the viewport,
  the layers and the selection; back on `/`, its bridge pushes the mirrored keys that differ from the
  store's initial state, and the server table catches up at once. The tradeoff: a server-rendered table
  needs `mirror` for everything its rendering depends on and costs a round trip per change, but the data
  can stay on the server; a client-rendered one costs no round trip and works offline, but the data must
  already be in the store, and the rendering code (filtering, ordering, empty states, escaping) is yours.
- **Logs** (`/logs`): 50,000 synthetic log entries (`Demo.Logs`, computed from their index, never stored)
  in a scroll container that renders only the rows in view. A chunk loader with `pageChunks` fetches the
  pages of 500 entries that those rows touch from `GET /api/logs?page=n`, as JSON, without a cache.
- **maplibrex** (`/maplibrex`): `<.map>` and `<.geojson_layer>` from maplibrex, with 300 places in the
  layer's `data` assign, and a table of the places in view. The `PlacesMap` hook creates the
  `map:places-map` store with `ensureStore`, binds it with maplibrex's `followMap` and `bindMap`, and removes
  it when the page goes. The viewport is mirrored; a click on a row or a point and the pointer over a point
  mark the place with feature state on `places-layer-source` and send nothing to the server, and the cursor
  is a pointer over a point. The components ask for no maplibrex events. **Re-score places** patches the
  layer data from the server, and the selection stays on the map.
- **Tasks** (`/tasks`): a task list driven by the persisted `tasks` store and the server actions
  `add_task`, `rename_task`, `toggle_task` and `remove_task`, all optimistic. The server keeps the list in
  memory (`Demo.Tasks`, an Agent shared by every LiveView process), runs each mutation id once, sends the
  authoritative list with `LiveSlice.patch/3` on mount and to the other open LiveViews after each change,
  and refuses a blank, too long or duplicate title, so adding the same title twice shows a rollback and its
  reason. Every task has a version; a rename or a tick is based on it, and the server answers one made on a
  task that changed since with a conflict (see [Conflicts](conflicts.md)). A conflicting rename shows a notice
  with the server's title; a conflicting tick is sent again on the new version by its resolver, and the
  notice says so. The page shows the connection state, how many changes are still being saved (from
  `onPending` and `onSettled`) and how many were never answered (kept as failed, from `onFailed` and
  `onRetry`), the last rejection (from `onRejected`) and the last conflict (from `onConflict`), and marks
  tasks with an unsaved change, or with a change that was not sent, with **Retry** and **Discard** (see
  [Failed pushes](persistence.md#failed-pushes)). Click **Rename** to edit a title in place (Enter or **Save** renames,
  Escape or **Cancel** keeps it).

  The list is drawn by a plain hook subscribed to the store, under `phx-update="ignore"`, not by the
  LiveView template: tasks added offline or still waiting for the server exist only in the client store.
  Hooks only mount once the LiveView has joined; when it cannot join, the offline mount runs the task hooks
  and the bridge instead (below).

  To try it offline, use the **Simulate offline** button, which calls `liveSocket.disconnect()` (and
  `liveSocket.connect()` to reconnect), or take the network away in the browser's developer tools once the
  page has loaded. Add, tick and remove tasks, reload the page while the socket is still down if you like,
  then reconnect: the changes reach the server once each, in order. To see a conflict, open the page in a
  second browser profile (a private window, so the two do not share the stored queue), rename a task there
  while the first one is offline, rename or tick the same task in the first one, and reconnect it.
- **Notes** (`/notes`): one note shared by every open tab and browser, the collaborative key `note` of the
  `notes` store, bound to the Yjs document `"notes:demo"` with three root types: a text in a plain `<textarea>`
  (a minimal diff binding, `assets/js/notes_store.js`), a checklist (add, tick, remove) and a counter kept per
  client, so that increments made at the same time add up. `DemoWeb.NotesLive` names the document and lets
  everyone read and write it; `Demo.CRDT` (with the in-memory persistence) holds the server's copy. The page
  shows the sync status, a **Simulate offline** button, and three buttons that read the note on the server
  (`LiveSlice.CRDT.get/3`), add an item from there (`LiveSlice.CRDT.change/4`) and delete the note
  (`LiveSlice.CRDT.delete/2`). Open it in two browsers (or a private window), type in both, take one offline,
  edit both, reconnect: everything merges. Take one offline, edit it, press **Delete note** in the other, and
  reconnect: the offline edits are dropped instead of bringing the old note back, and the page says so. The
  note is kept in IndexedDB, so it survives a reload, also offline with the service worker. Restarting the
  server loses its copy, and forgets a delete; the first client that syncs gives the note back (see
  [Offline, tabs and restarts](collaborative-keys.md#offline-tabs-and-restarts)).
- **Offline cold start**: with the service worker on (`DEMO_SERVICE_WORKER=1 mix phx.server`; it is on in
  production and off otherwise), the pages open with the server stopped. `assets/js/sw.js` keeps `/`,
  `/map-client`, `/tasks`, `/notes` and `/logs` at install and every page when visited, the built assets, and
  the `/api/logs` pages network first. app.js lists the hooks that need no server for the offline mount: the
  bridge, the task hooks, the note hooks, the map, its panels, the client table and the log list (not
  maplibrex's). While they run, the page says so in a banner. `/tasks` draws the saved list and queues
  changes; the map draws the tiles of the last dataset version kept in IndexedDB (the map store keeps that
  version), on a plain background when the basemap style cannot load, and `/map-client` lists their
  features in its table, which `/` cannot without its server; `/logs` shows the pages it kept and says which
  rows could not be loaded; `/maplibrex`
  shows its saved page without a map. When the server is back, the LiveView joins and its hooks take over.
  A new asset build shows a "new version" notice whose button switches to it. `resetServiceWorker()` in the
  console removes the worker and its caches; the server keeps the task list in memory, so restarting it
  forgets the tasks it had confirmed.

```sh
cd demo
mix setup        # deps, esbuild and tailwind, npm install in assets/, asset build
mix phx.server   # then open http://localhost:4000 (set PORT to change the port)
DEMO_SERVICE_WORKER=1 mix phx.server   # the same, with the service worker
```

`mix setup` needs Node.js and npm. The basemap style and tiles come from `demotiles.maplibre.org`; without
network access the points of `/` render on a plain background, while the `/maplibrex` map has no fallback
style. The demo imports the library as `live_slice` through an npm `file:` link to this repository, and
maplibrex from Hex. It installs `maplibre-gl` from npm and copies its worker next to `app.js` with a second
esbuild profile, because the bundled `app.js` has no `import.meta.url` from which maplibre-gl could locate
it. A third profile, `service_worker`, bundles `assets/js/sw.js`.
