# JavaScript API

MaplibreX's components create MapLibre maps in the browser and keep
sources, layers, markers and controls on them. Your own JavaScript can work
with those maps too: listen to MapLibre events, set feature state, drive a
map from a client-side store. This guide lists what the `maplibrex` package
exports for that, and the rules for touching what the components manage.

## What is public

These exports of `maplibrex` are public, and covered by the version number
as the components are: a change that breaks one of them is a breaking
change, listed under "Breaking" in the changelog (while MaplibreX is below
1.0, in a new minor version).

* `MapHooks`, also the default export: the hooks to give `LiveSocket` (see
  the README).
* `MapManager`, the registry of the maps on the page, with its methods
  `whenReady`, `whenNextRegistered`, `get` and `isRegistered`.
* `useMap`, `requireMap` and `followMap`.
* For TypeScript, the types of their callbacks: `MapReadyCallback`,
  `MapAttach` and `MapDetach`.

The rest of what the package exports is internal; see
[Internal exports](#internal-exports).

Import them from the same `maplibrex` as `MapHooks`:

```javascript
import { MapManager, followMap, useMap, requireMap } from "maplibrex"
```

`MapManager` is one object in the bundle. A second copy of MaplibreX in
your JavaScript, imported by another path, would have a registry of its
own, with no maps in it.

The signatures below are TypeScript, with MapLibre's map type:
`import type { Map } from "maplibre-gl"`.

## The maps on the page

The map hook registers each map under the `id` of its `<.map>` as soon as
MapLibre creates it, before its style has loaded, and unregisters it just
before it removes it, when its element goes. Code given a map can listen to
its events at once; MapLibre refuses changes to the style (a source or a
layer added, feature state set) until the style has loaded.

A `<.map>` can be rendered again under the same id: behind `:if`, say, or
by a patch that replaces its element. That makes a new map: the old one is
removed, with every listener, source and layer on it, and the new one is
registered under the same id. `followMap` follows the map from one to the
next; the other functions deal with one map.

### `MapManager.whenReady(mapId, callback)`

```typescript
whenReady(mapId: string, callback: (map: Map) => void): () => void
```

Calls `callback` with the map registered under `mapId`: right away, before
`whenReady` returns, if there is one, and otherwise once one is registered.
It is called at most once, and only for a map registered under `mapId`:
other maps coming and going leave it waiting. If no such map ever comes, it
is never called, and waits until the function `whenReady` returns cancels
it (that function does nothing once the callback has run). A callback that
throws is logged in the console and does not stop the others.

```javascript
import { MapManager } from "maplibrex"

// Runs now if the map is registered, or once it is.
const cancel = MapManager.whenReady("map", map => {
  map.on("moveend", onMove)
})
```

It runs once: a map rendered again under the same id does not call it
again. `followMap` does.

### `MapManager.whenNextRegistered(mapId, callback)`

```typescript
whenNextRegistered(mapId: string, callback: (map: Map) => void): () => void
```

As `whenReady`, except that it always waits for the next map registered
under `mapId`, even when one is registered now.

### `MapManager.get(mapId)`

```typescript
get(mapId: string): Map | undefined
```

The map registered under `mapId` now, or `undefined`. It logs nothing
either way, so it is the way to ask whether a map exists:
`MapManager.get(mapId) !== undefined`. Code that needs the map and has
none uses `requireMap`, which complains; code that can wait for it uses
`whenReady` or `followMap`.

### `MapManager.isRegistered(mapId, map)`

```typescript
isRegistered(mapId: string, map: Map): boolean
```

Whether `map` is the map registered under `mapId` now: false once it has
been unregistered, or another map has been registered in its place.

### `useMap(mapId)`

```typescript
useMap(mapId: string): Map | undefined
```

The same as `MapManager.get(mapId)`.

### `requireMap(mapId)`

```typescript
requireMap(mapId: string): Map
```

The map registered under `mapId`. With none, it warns in the console, then
throws an `Error`; both name `mapId`.

### `followMap(mapId, attach)`

```typescript
followMap(mapId: string, attach: (map: Map) => (mapRemoved: boolean) => void): () => void
```

Follows the map registered under `mapId`, from one map to the next. It
calls `attach` with the map as soon as there is one, right away if there
is. `attach` returns a cleanup function. When the map is removed (its
`remove` event), `followMap` calls the cleanup with `true`, then `attach`
again with the map registered under `mapId` in its place: the one already
registered, when a patch replaced the map's element, or else the next one
registered.

With `true`, the map is gone, and the listeners on it with it: there is
nothing to undo on it. The cleanup is called before any `remove` listener
that `attach` added to the map.

The function `followMap` returns stops following. With a map attached, it
calls the cleanup with `false`: the map stays, and the cleanup undoes what
`attach` did to it. Otherwise it stops waiting. Calling it again does
nothing.

An `attach` that throws is logged in the console, and the next map is
followed all the same. A cleanup that throws when its map is removed is
logged and does not stop the map's other `remove` listeners; one that
throws when the function `followMap` returned calls it throws from that
function.

```javascript
import { followMap } from "maplibrex"

const stop = followMap("map", map => {
  map.on("click", onClick)
  // true: the map was removed, listeners and all; false: stop() was called.
  return mapRemoved => {
    if (!mapRemoved) map.off("click", onClick)
  }
})
```

The types `MapAttach` and `MapDetach` name `attach` and its cleanup, and
`MapReadyCallback` the callback of `whenReady` and `whenNextRegistered`.

## What the components own

Each component keeps these on the map registered under its `map_id`;
`<id>` is the component's `id`:

| Component | On the map |
| --- | --- |
| `map` | the map, registered under `<id>` |
| `geojson_layer` | a GeoJSON source `<id>-source`, and a layer `<id>` that draws it |
| `circle_layer`, `line_layer`, `fill_layer`, `symbol_layer`, `heatmap_layer`, `fill_extrusion_layer`, `hillshade_layer`, `raster_layer` | a layer `<id>`, which draws the source `source_id` (not its own) |
| `background_layer` | a layer `<id>` |
| `vector_tile_source`, `raster_tile_source`, `raster_dem_source`, `image_source`, `video_source` | a source `<id>` |
| `custom_layer`, `flow_layer` | a custom layer `<id>` |
| `deckgl_layer` | a deck.gl layer `<id>`, in a deck.gl overlay that the map's `deckgl_layer`s share; deck.gl adds MapLibre layers of its own for it, under ids of its own |
| `terrain` | the map's terrain, from the source `source_id`: no source or layer |
| `sky` | the map's sky: no source or layer |
| `marker`, `popup` | a MapLibre `Marker` or `Popup`: no source or layer |
| the control components | a control: no source or layer |
| `zoom_range` | nothing: it listens to the map's zoom |

A component whose layer or source id is already on the map, from the map's
style or from your code, takes that layer or source over: it changes it,
and leaves it on the map when it goes.

## Working with what the components manage

### Paint, layout, filter and data

A component applies its attributes. It changes a property of its layer when
the rendered value of that property changes (to MapLibre's default when
the attribute leaves it out), and `geojson_layer` gives its source new data
when `data` changes. After a style change, and on a map rendered again
under its id, it puts its layer and source back from its attributes (and,
for `geojson_layer`, from the commands it was given).

So a value your code sets on a component's layer or source, with
`setPaintProperty`, `setLayoutProperty`, `setFilter` or `setData`, lasts
until the next render that changes that property, or the next style
change. A change that has to last belongs in the attributes, or, for
`geojson_layer`, in its commands (see `MaplibreX.Components.GeoJSONLayer`),
which your JavaScript can dispatch too, and which last through style
changes. To take a component's layer or source off the map, remove the
component.

### Feature state

Feature state is your application's: no component sets it, and none puts
it back. MapLibre keeps it with the source. New data, which `geojson_layer`
gives its source with `setData`, keeps the state of each feature id; a
source added again starts with none. A component's source is added again:

* on each style change made through the map
  (`MaplibreX.Components.Map.set_style/2`, `map:set_style`, a new `style`
  attribute): MapLibre diffs the new style in, which
  removes the sources it does not have, the components' among them, and
  the components add theirs back; or, when it cannot diff (with terrain on,
  say), it rebuilds the style from scratch;
* when it changes in a way the source cannot take in place: for
  `geojson_layer`, turning `cluster` off, or a new `cluster_properties`,
  `generate_id` or `promote_id`;
* on a map rendered again under its id, which is a new map.

A source of the map's style that the new style has too, unchanged, keeps
its state through a diff, but not through a rebuild.

So set the state again on each new source object. Feature state needs
feature ids, from one of:

* an `id` on each GeoJSON feature;
* a property named by `promote_id`: with `promote_id="uuid"`, each
  feature's `uuid` property is its id, string or number, so
  `setFeatureState({ source: "<id>-source", id: feature.properties.uuid }, ...)`
  addresses it, whatever the order of the data;
* `generate_id={true}`, which numbers the features in the order of the
  data, so that a feature's id changes when a feature before it comes or
  goes. It excludes `promote_id`.

Here the layer is `<.geojson_layer id="quakes" ...>`, whose source is
`quakes-source`; when the user selects a quake, the application adds its
id to `selected` and sets its state as usual.

```javascript
import { followMap } from "maplibrex"

// The ids of the quakes the user selected: the application keeps them.
const selected = new Set()

followMap("map", map => {
  let source
  // A source added again has no feature state: set it on each new one.
  const restore = () => {
    const current = map.getSource("quakes-source")
    if (!current || current === source) return
    source = current
    for (const id of selected) {
      map.setFeatureState({ source: "quakes-source", id }, { selected: true })
    }
  }
  const onSourceData = event => {
    if (event.sourceId === "quakes-source") restore()
  }
  map.on("sourcedata", onSourceData)
  restore()
  return mapRemoved => {
    if (!mapRemoved) map.off("sourcedata", onSourceData)
  }
})
```

### Sources and layers of your own

A source or layer your code adds goes with each style change made through
the map: a diff keeps only what the new style has, and a rebuild keeps
nothing. A custom layer is the exception on a diff, which does not see
custom layers and leaves them where they are, under the new style's
layers; a rebuild drops it too. All of them go with the map. For a source
or layer that has to stay, use a component; otherwise add yours again after
each style change, and on each new map, which `followMap` gives you.

## Internal exports

The package exports more than this guide documents. The rest is
MaplibreX's own, and may change in any release:

* the other methods of `MapManager`: `register`, `unregister`,
  `getOrThrow`, `has`, `getAll`, `getAllIds`, `count`, `clear` and
  `setDebug`;
* `EventDispatcher` and `createEventDispatcher`, which connect a map to the
  LiveView of its hook;
* the hooks one by one (`MapHook`, `MarkerHook` and the others), the
  objects `MapHooks` holds, under the same names: register `MapHooks`,
  which has every hook the components name;
* the types `LiveViewHook`, `HookContext`, `MapConfig`, `MarkerConfig`,
  `PopupConfig`, `LayerConfig`, `GeoJSONSourceConfig`, `ControlConfig`,
  `NavigationControlConfig`, `ScaleControlConfig`,
  `FullscreenControlConfig`, `GeolocateControlConfig`, `MapEventPayload`,
  `MapMoveEventPayload`, `MapClickEventPayload`, `MarkerDragEventPayload`,
  `Position` and `Bounds`.
