# MapLibre binding

Maps are one integration among others: the core entry knows nothing about them. The optional entry
`live_slice/maplibre` binds a store to a [MapLibre GL JS](https://maplibre.org/) map that the app passes in.
It imports nothing (no runtime dependencies, no `maplibre-gl` import) and uses only the map's public API:
`on`, `off`, `getSource`, `getLayer`, `setFeatureState`, `removeFeatureState`, `queryRenderedFeatures`,
`listImages`, `getCanvas`, the camera getters and `jumpTo`.

```js
import { bindMap } from "live_slice/maplibre";

const unbind = bindMap(store, map, {
  viewport: {},
  selection: { sources: ["places"], layers: ["places-layer"], clearOnMiss: true, cursor: "pointer" },
  hover: { sources: ["places"], layers: ["places-layer"] },
});

// Later, when the hook goes: removes every listener and subscription, unmarks the features and
// puts the cursor back.
unbind();
```

Each option is optional; `bindMap` binds only what it is given.

- **`viewport`** writes the map's camera to a store key when bound and once per `moveend`.
  - `key` (`"viewport"`), `events` (`["moveend"]`).
  - `read(map)` returns the value to store; by default (exported as `readViewport`)
    `{center: [lng, lat], zoom, bearing, pitch, bounds: [west, south, east, north]}`. It must return plain
    JSON: the bridge compares mirrored values by content, so a copy of the same viewport is never pushed,
    and the binding writes nothing when the value did not change.
  - `initial: false` skips the write when bound (`moveend` does not fire for the initial camera).
  - `apply: true` moves the map with `jumpTo` (`center`, `zoom`, `bearing`, `pitch`) when the key is
    changed from outside; `apply: (map, value) => ...` moves it any other way (`easeTo`, `fitBounds`). A
    value the key already holds when bound (a deep link, a server patch, the camera of the map bound
    before) moves the map too, before its first report; without one the map stays where it is. A value
    equal to the map's own last report is never applied back, so there is no feedback loop.
- **`selection`** and **`hover`** keep a feature id in a store key (`"selectedId"`, `"hoveredId"`) and mark
  that feature with feature state (`{selected: true}`, `{hover: true}`; `state` changes the name) in every
  listed source, unmarking the previous one. `sources` are source ids or `{source, sourceLayer}` (vector
  sources need their source layer). With `layers`, a click (selection) or the pointer (hover) over a
  feature of those layers writes its id: a click on no feature keeps the selection unless `clearOnMiss` is
  true, and the hover is cleared over no feature and when the pointer leaves the map (`mouseout`; MapLibre's
  `mouseleave` only exists per layer). The hover is written only when the id changes. Without `layers`, the
  store drives the map only. Paint the layers with the `feature-state` expression, for example
  `["case", ["boolean", ["feature-state", "selected"], false], 9, 4]`. Features need stable ids, numbers or
  strings: a top-level `id` in GeoJSON, or the source's `promoteId`.
  - `cursor` (a CSS cursor, such as `"pointer"`; it needs `layers`) shows that cursor on the map's canvas
    (`map.getCanvas().style.cursor`) while the pointer is over a feature with an id of those layers, and puts
    back the one it had when the pointer is over none or leaves the map, and on `unbind`, unless someone else
    changed it meanwhile. Give it to `selection` to show that a click selects. A `selection` without it does
    not watch the pointer at all; with `hover` over the same layers, the two share one query per pointer move.
- **`onStyleChange(map)`** is called after a style change (a new basemap), diffed or rebuilt, dropped a
  source that was on the map, once the new style accepts sources and layers again. Every style change drops
  the sources and layers the app added itself, so add them back there. The sources watched are
  `ownSources` (source ids), or else the `selection` and `hover` sources. `ownSources` may also be a
  function `(map) => ids`, asked at each style event for the sources the app keeps on the map now: see
  [Own sources and managed ones](#own-sources-and-managed-ones) for when that matters.

`unbind(mapRemoved)` is idempotent and harmless on a map that was removed already; with `true` it does not
touch the map's feature state or its cursor. The store's state stays as it is, so a map bound later (a map
created again) shows the same selection.

## Re-applying feature state

Feature state belongs to a source object. New data (`setData`) keeps it; a source added again starts without
it. That happens to a source more often than one might think: a source the app added goes with every style
change, diffed or rebuilt, and a source a component library manages is added again on every style change
too, when the component replaces its source, and on a new map. maplibrex's
[JavaScript API guide](https://hexdocs.pm/maplibrex/0.4.0/javascript-api.html#feature-state)
("Feature state") spells this out and gives the recipe the binding follows: remember the source object the
marks were set on, and set them again on each new one. The binding checks on `sourcedata` of a listed source
and on `styledata` and `style.load`, so data updates and events about the same source set nothing again.

It is built for the cases a map meets in practice:

- The map can be bound before its style or its sources exist. A mark for a source that does not exist yet
  waits for the source; a feature state call while the style is loading (MapLibre throws "Style is not
  done loading.") is retried on the next event. Pointer queries skip `layers` that do not exist yet, since
  MapLibre reports a query naming a missing layer as an error.
- Style events can fire synchronously from inside a feature state call or a style change (a render that a
  library forces before diffing a style): the binding ignores events that arrive while it is applying
  marks or running `onStyleChange`, and it never listens to `render`.
- Only feature state is touched: never paint, layout, filters or data.

## Own sources and managed ones

A source the app adds itself with `map.addSource` belongs to the app: every style change drops it with its
layers (a diff keeps only what the new style has, a rebuild keeps nothing), and only the app can add them
back, in `onStyleChange`:

```js
const addPlaces = (map) => {
  if (!map.getSource("places")) map.addSource("places", { type: "geojson", data: placesGeoJSON });
  if (!map.getLayer("places-layer")) {
    map.addLayer({
      id: "places-layer",
      type: "circle",
      source: "places",
      paint: { "circle-radius": ["case", ["boolean", ["feature-state", "selected"], false], 9, 4] },
    });
  }
};

addPlaces(map);
bindMap(store, map, {
  selection: { sources: ["places"], layers: ["places-layer"] },
  // The selection is marked again once the source is back.
  onStyleChange: addPlaces,
});
```

MapLibre has no event that tells a style change on every path: maplibre-gl 6 fires `style.load` after a
diffed style change too, but maplibre-gl 5 does not, and a diff fires the same `sourcedata` and `styledata`
as the app's own `map.removeSource`. So the binding takes a watched source that was on the map and is gone at
a style event for a style change. An app that removes one of its sources on purpose (a dataset turned off)
says so with an `ownSources` function, which returns the sources it keeps on the map now; a source it no
longer returns is not watched, and has to be seen on the map again before its absence counts:

```js
bindMap(store, map, {
  selection: { sources: ["places"], layers: ["places-layer"] },
  ownSources: () => (store.getState().showPlaces ? ["places"] : []),
  onStyleChange: (map) => store.getState().showPlaces && addPlaces(map),
});
```

The demo's `/` page adds its own source and layers the same way; it never changes its basemap, so it passes
no `onStyleChange`. A source that a component library manages (for example maplibrex's
`<.geojson_layer>`) comes back by itself after a style change, as a new source; the binding marks it again.
Either way, the binding needs no other knowledge of who owns a source. On a new map (a map element rendered
again), bind again: maplibrex's `followMap` below does that.

## maplibrex

[maplibrex](https://hex.pm/packages/maplibrex) renders MapLibre maps as LiveView components (`<.map>`,
`<.geojson_layer>`, ...). Tested with maplibrex 0.4.0 from Hex, maplibre-gl 6.18.0, Phoenix LiveView 1.2.15
and Phoenix 1.8.17 (the demo's `/maplibrex` page). `live_slice` never imports maplibrex: the app reaches
maplibrex's maps with maplibrex's own `followMap` and hands each one to `bindMap`. maplibrex's public
JavaScript contract is its [JavaScript API guide](https://hexdocs.pm/maplibrex/0.4.0/javascript-api.html):
what it exports, which source and layer ids each component owns, and when feature state is lost; the binding
and the rules below follow it.

```heex
<%!-- No events: the LiveView handles none of the components' events. --%>
<.map
  id="places-map"
  style="https://demotiles.maplibre.org/style.json"
  center={[3.0, 44.0]}
  zoom={4}
  class="h-full w-full"
/>
<.geojson_layer id="places-layer" map_id="places-map" type="circle" data={@data} paint={@paint} />
```

```js
import { ensureStore, removeStore } from "live_slice";
import { bindMap } from "live_slice/maplibre";
import { followMap } from "maplibrex";

export const PlacesMap = {
  mounted() {
    const store = ensureStore("map:places-map", {
      state: { viewport: null, selectedId: null, hoveredId: null },
    });
    const features = { sources: ["places-layer-source"], layers: ["places-layer"] };
    this.stopFollowing = followMap("places-map", (map) =>
      bindMap(store, map, {
        viewport: {},
        selection: { ...features, clearOnMiss: true, cursor: "pointer" },
        hover: features,
      }),
    );
  },
  destroyed() {
    this.stopFollowing();
    removeStore("map:places-map");
  },
};
```

This is the demo's `PlacesMap` hook (`demo/assets/js/places_hooks.js`, which takes `followMap` as an argument
so that its tests can pass a fake). `followMap(mapId, attach)`, exported by maplibrex from 0.4.0, calls
`attach(map)` as soon as maplibrex registers a map under `mapId` (at once if one is). When that map is removed
it calls what `attach` returned with `true` (the map is gone, listeners and all) and attaches to the map
registered in its place, or to the next one: maplibrex creates a new map when the `<.map>` element is rendered
again. The function it returns stops following and calls the cleanup with `false`. `bindMap` returns a
cleanup that takes that `mapRemoved` flag, so it is returned from `attach` as is.

Rules that keep the two libraries out of each other's way:

- Reach maps only through `followMap` and `MapManager` (`whenReady`, `whenNextRegistered`, `get`,
  `isRegistered`); never `register` or `unregister` them. maplibrex registers a map right after creating it,
  before its `load` event, so `attach` may get a map whose style and sources do not exist yet; `bindMap` copes
  with that. From 0.4.0, `MapManager.get(mapId)` returns `undefined` for a missing map without a warning;
  `requireMap(mapId)` warns and throws.
- Feature state on a managed source, yes: it is how hover and selection should be drawn. Paint, layout,
  filters and data of a managed layer or source, no: drive those through assigns (a value set from
  JavaScript lasts only until the next render that changes it, or the next style change). maplibrex names
  the source of `<.geojson_layer id="places-layer">` `places-layer-source` (`<id>-source`); the guide's
  table lists the ids of every component.
- Feature state on a component's source is lost on every style change, diffed or rebuilt, when
  `<.geojson_layer>` replaces its source (turning `cluster` off, a new `cluster_properties`, `generate_id` or
  `promote_id`) and on a map rendered again; new `data` keeps it. `bindMap` marks each new source again;
  sources and layers you add yourself need `onStyleChange`.
- Features need stable ids: a top-level `id` on each GeoJSON feature (the demo gives each place a numeric
  one), or, from 0.4.0, `promote_id` on `<.geojson_layer>`, which takes each feature's id from a property and
  passes it to the source as `promoteId`: with `promote_id="uuid"`, the store's `selectedId` holds a
  feature's `uuid`, a string or a number. Avoid `generate_id`: it numbers features by position, which changes
  with the data, and it excludes `promote_id`. 0.4.0 also takes a URL as `data`.
- Do not render the mirrored viewport back into `<.map>`: keep its `center` and `zoom` the ones it opened
  with, or every report would move the map again.
- Events are opt-in from 0.4.0: a component pushes only the events its `events` attribute names, and none
  without it. When the store carries the interaction, give the components no `events`, or only those your
  LiveView handles; `bindMap` listens on the MapLibre map itself, so selection and hover send nothing over
  the websocket. The demo's LiveView handles none, so its `<.map>` and `<.geojson_layer>` have no `events`.
  (On 0.3.x, which pushes every event without an `events` list, pass `events={[]}`.)
- From 0.4.0 a layer that asks for no `layer:feature_*` event shows no pointer cursor over its features.
  Give `bindMap`'s `selection` a `cursor: "pointer"` rather than asking for `layer:feature_clicked` for the
  cursor's sake, which would push every click on a feature to the LiveView.
- `MapHooks` adds 33 keys to the LiveSocket's `hooks` (`MapHook`, `MarkerHook`, `GeoJSONLayerHook`, ...;
  maplibrex's README lists them). A hook of your own under one of those names silently replaces maplibrex's,
  or is replaced, whichever spread comes last: give your hooks other names (the demo's own map hook is
  `FeatureMap`).
- Setup, from maplibrex's README: install `maplibre-gl` in `assets/` within maplibrex's peer range
  (`>=5.0.0 <7.0.0` for 0.4.0). The bundle in `deps/maplibrex` imports `maplibre-gl` from
  `assets/node_modules`, so add `Path.expand("../assets/node_modules", __DIR__)` to the `NODE_PATH` of the
  esbuild profile: the app and maplibrex then share one copy (the demo's `app.js` bundles a single
  `maplibre-gl` module). Add `--external:@deck.gl/*` to its `args` unless deck.gl is installed; with
  `<.deckgl_layer>`, 0.4.0 needs deck.gl 9.4 with `@deck.gl/maplibre` in place of `@deck.gl/mapbox`. Import
  `../../deps/maplibrex/assets/css/maplibrex.css` in `app.css`. With maplibre-gl 6, copy its worker next to
  `app.js` and call `setWorkerUrl` (the demo does it with a second esbuild profile; maplibrex 0.4.0 also has
  `mix maplibrex.copy_worker`).
- Upgrading from maplibrex 0.3.0: its changelog's
  [Upgrading from 0.3.0](https://hexdocs.pm/maplibrex/0.4.0/changelog.html#upgrading-from-0-3-0) lists every
  change. For a map bound with `live_slice`: follow it with maplibrex's `followMap(...)` as above, drop the
  `events={[]}` that silenced 0.3.0, add `cursor: "pointer"` to the selection, and read the data of
  `<.geojson_layer>` from `data-geojson` rather than `data-config` in tests that decode the rendered markup.
